<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Repositories\WxContRepositories;
use App\Http\Controllers\Api\Repositories\WxUserReportRepositories;

use App\Jobs\User\UserWithdrawalProcessJob;
use App\Jobs\UserBgColorUpdateJob;
use App\Jobs\UserInputSafeCheckJob;
use App\Lib\WeApp\WeApp;
use App\Mail\text;
use App\Models\Bureau\WxBureau;
use App\Models\Pets\WxPetsAdoption;
use App\Models\Posts\WxComment;
use App\Models\User\WxUserAvatarFrame;
use App\Models\User\WxUserCoinRecord;
use App\Models\User\WxUserContactApply;
use App\Models\User\WxUserFinancialRecord;
use App\Models\User\WxUserInviteBenefitRecord;
use App\Models\User\WxUserInviteTempCode;
use App\Models\User\WxUserInviteTempCodeRecord;
use App\Models\User\WxUserOnline;
use App\Models\User\WxUserReport;
use App\Models\User\WxUserSetting;
use App\Models\User\WxUserVisit;
use App\Models\Voter\WxVoter;
use App\Models\WxAttachment;
use App\Wen\Utils\BaiduUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\SafeUtils;
use App\Wen\Utils\SearchUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\SiteUtils;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxUserRepositores;
use App\Models\Posts\WxCollect;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsVote;
use App\Models\Posts\WxUserCircle;
use App\Models\WxAuthentication;
use App\Models\Circle\WxCircle;
use App\Models\WxCommentLike;
use App\Models\WxExceptional;
use App\Models\WxOrder;
use App\Models\WxPlate;
use App\Models\User\WxUser;
use App\Models\User\WxUserFinancial;
use App\Models\User\WxUserFollow;
use App\Models\User\WxUserPlate;
use App\Models\User\WxUserVote;
use App\Models\User\WxUserWithdrawal;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Lib\wxBizDataCrypt\WxBizDataCrypt;
use App\Lib\JwtAuth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Laravel\Socialite\Facades\Socialite;
use Overtrue\Pinyin\Pinyin;
use SimpleSoftwareIO\QrCode\Facades\QrCode;


class UserController extends BaseController
{

    public function user_process(Request $request){
        $type = _empty_default_($request->type, '');
        if ($type == 'contact_apply') {
            return $this->contactApply($request);
        }else if($type == 'contact_apply_query'){
            return $this->contact_apply_query($request);
        }else if($type == 'anonymous_info'){
            return $this->anonymous_info($request);
        }else if($type == 'circle_unread_count_19'){
            return $this->circle_unread_count_19($request);
        }else if($type == 'circle_unread_count_remove'){
            return $this->circle_unread_count_remove($request);
        }else if($type == 'invite_tmp_code_query'){
            return $this->invite_tmp_code_query($request);
        }else if($type == 'invite_tmp_code_bind'){
            return $this->invite_tmp_code_bind($request);
        }else if($type == 'invite_info_query'){
            return $this->invite_info_query($request);
        }else if($type == 'invite_info_update'){
            return $this->invite_info_update($request);
        }
    }

    private function invite_info_update(Request &$request){
        global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
        if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
            return $this->fail(200000);
        }
        $user_id = _empty_default_($request->user_id, 0);
        if(_empty_($user_id)){
            return $this->fail(200001);
        }
        $invite_benefit = _empty_default_($request->invite_benefit, 0);
        if(!_empty_($invite_benefit)){
            $invite_benefit = round((float)$invite_benefit, 2);
            if($invite_benefit <= 0){
                return $this->fail(200004);
            }
        }else{
            $invite_benefit = 0;
        }

        $invite_benefit_layer = _empty_default_($request->invite_benefit_layer, 0);
        if(!_empty_($invite_benefit_layer)){
            if(_empty_($invite_benefit_layer) || !in_array($invite_benefit_layer, [1,2,3])){
                return $this->fail(200001);
            }
        }else{
            $invite_benefit_layer = 0;
        }
        if($invite_benefit === 0 && $invite_benefit_layer === 0){
            return $this->fail(200001);
        }

        $user = WxUser::where('id', $user_id)->first(['id', 'user_name', 'user_avatar', 'invite_benefit', 'invite_benefit_layer']);
        if(_empty_($user)){
            return $this->fail(200003);
        }

        if($invite_benefit > 0){
            WxUser::withoutSyncingToSearch(function () use (&$user, $invite_benefit){
                WxUser::where('id', $user->id)->update(['invite_benefit'=>$invite_benefit]);
            });
        }else if($invite_benefit_layer > 0){
            WxUser::withoutSyncingToSearch(function () use (&$user, $invite_benefit_layer){
                WxUser::where('id', $user->id)->update(['invite_benefit_layer'=>$invite_benefit_layer]);
            });
            if($invite_benefit_layer > 1){
                Cache::put('is:can:bind:itc:'.$user->id, '1', 3600);
            }
            GatewayUtils::success(GatewayUtils::uid2client_id($user->id), 12);
        }
        $user = WxUser::where('id', $user_id)->first(['id', 'user_name', 'user_avatar', 'invite_benefit', 'invite_benefit_layer']);
        if(_empty_($user)){
            return $this->fail(200003);
        }
        return $this->success($user);
    }

    private function invite_info_query(Request &$request){
        $user_id = _empty_default_($request->user_id, 0);
        if(_empty_($user_id)){
            return $this->fail(200001);
        }
        $user = WxUser::where('id', $user_id)->first(['id', 'user_name', 'user_avatar', 'invite_benefit', 'invite_benefit_layer']);
        if(_empty_($user)){
            return $this->fail(200003);
        }
        if($user->invite_benefit == -1){
            $user->invite_benefit = Settings::get('user_invite_immediately_benefit_blance', 0.0);
        }
        return $this->success($user);
    }

    private function invite_tmp_code_bind(Request &$request){
        $uid = $request->uid;
        global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
        if(_empty_($uid)){
            return $this->fail(200001);
        }
        $itc = _empty_default_($request->itc, '');
        if(_empty_($itc)){
            return $this->fail(200001);
        }
        if(!StrUtils::startsWith($itc, 'itc')){
            return $this->fail(200004);
        }
        $itc = (int)(str_replace('itc', '', $itc));
        if($itc <= 0){
            return $this->fail(200004);
        }

        $itc_obj = WxUserInviteTempCode::find($itc);
        if(_empty_($itc_obj)){
            return $this->fail(200003);
        }
        $type_arr = [1=>'传单', 2=>'桌牌'];
        $itc_obj->type_tip = $type_arr[$itc_obj->type];
        if($itc_obj->status == 1){
            return $this->fail(200010, [], '该'.$itc_obj->type_tip.'已绑定');
        }
        $user = WxUser::find($uid);
        if(_empty_($user)){
            return $this->fail(200001);
        }
        if($user->invite_benefit_layer <= 1){
            if($__MINI_GLOBAL_IS_ADMIN_SUPER__){

            }else{
                return $this->fail(200000, [], '仅推广专员，校园合伙人可绑定');
            }
        }
        if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
            if(!Cache::has('is:can:bind:itc:'.$user->id)){
                return $this->fail(200000, [], '绑定传单需要联系管理员');
            }
        }
        $updates = [
            'user_id' => $user->id,
            'status' => 1
        ];
        if($itc_obj->tenant_id === null){
            $updates['tenant_id'] = $user->tenant_id;
        }
        WxUserInviteTempCode::where('id', $itc_obj->id)->update($updates);
        return $this->success();
    }

    private function invite_tmp_code_query(Request &$request){
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200001);
        }
        $itc = _empty_default_($request->itc, '');
        if(_empty_($itc)){
            return $this->fail(200001);
        }
        if(!StrUtils::startsWith($itc, 'itc')){
            return $this->fail(200004);
        }
        $itc = (int)(str_replace('itc', '', $itc));
        if($itc <= 0){
            return $this->fail(200004);
        }

        $itc_obj = WxUserInviteTempCode::find($itc);
        if(_empty_($itc_obj)){
            return $this->fail(200003);
        }
        $type_arr = [1=>'传单', 2=>'桌牌'];
        $status_arr = [0=>'待绑定', 1=>'已绑定', 2=>'解除绑定'];

        $itc_obj->type_tip = $type_arr[$itc_obj->type];
        $itc_obj->type_img = env('APP_URL', '').'/statics/images/invite_tmp_code/itc_type_'.$itc_obj->type.'.png';
        $itc_obj->desc = '绑定之后，您可以使用该'.$itc_obj->type_tip.'进行推广，奖励会自动关联到您的账号';
        $itc_obj->status_tip = $status_arr[$itc_obj->status];
        $itc_obj->title = ($itc_obj->status == 1 ? '您已' : '您可').'绑定该'.$itc_obj->type_tip.'(id:'.$itc_obj->id.')';
        if($itc_obj->status == 1){
            if($itc_obj->user_id == $uid){
                $itc_obj->status_tip = '您已绑定';
            }else{
                $itc_obj->status_tip = '已被他人绑定';
            }
        }
        $result = DB::table('wx_user_invite_temp_code_record')
            ->select(
                DB::raw('COUNT(object_id) as total_objects'),
                DB::raw('SUM(reward_balance) as total_reward_balance'),
                DB::raw('SUM(reward_coin) as total_reward_coin')
            )
            ->where('itc_id', $itc_obj->id)
            ->first();
        $itc_obj->invite_info = $result;
        $itc_obj->result_tip = '共'.$result->total_objects.'人 (奖励￥'.$result->total_reward_balance.'+'.Settings::get('app_coin_name', '硬币').'*'.$result->total_reward_coin.')';
        return $this->success($itc_obj);
    }

    private function circle_unread_count_remove(Request &$request){
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200001);
        }

        DB::table('wx_user_visit')
            ->where('user_id', $uid)
            ->where('type', 2)
            ->whereIn('object_id', function ($query) use ($uid) {
                $query->select('uc.circle_id')
                    ->from('wx_user_circle as uc')
                    ->join('wx_circle as c', 'uc.circle_id', '=', 'c.id')
                    ->where('uc.user_id', $uid)
                    ->where('uc.user_circle_state', 0)
                    ->where('c.circle_state', 1);
            })
            ->update(['updated_at' => Carbon::now()]);

        Cache::forget('user_circle_unread_count:'.$uid);

        return $this->success();
    }

    private function circle_unread_count_19(Request &$request){
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200001);
        }
        $app_find_tab = Settings::get('app_find_tab', [], true);
        $flag = false;
        if($app_find_tab){
            for ($i = 0; $i < count($app_find_tab); $i++){
                if($app_find_tab[$i]['follow_status'] == 1 && _empty_($app_find_tab[$i]['tags'])){
                    $app_find_tab[$i]['badge'] = [
                        'value' => UserUtils::user_circle_unread_count($uid)
                    ];
                    $flag = true;
                }
            }
        }
        if($flag){
            return $this->success($app_find_tab);
        }else{
            return $this->fail(200003);
        }
    }

    private function anonymous_info(Request &$request){
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200001);
        }
        $change = _empty_default_($request->change, 0) == 1 ? 1 : 0;
        $the_user = WxUser::find($uid);
        if($the_user){
            $anonymous_info = UserUtils::get_anonymous_info($the_user, $change);
            if($anonymous_info){
                return $this->success($anonymous_info);
            }
        }
        return $this->fail(200003);
    }

    public function contact_apply_query(Request &$request){
        $uid = _empty_default_($request->uid, 0);
        if(_empty_($uid)){
            return $this->fail(503002);
        }
        $object_id = _empty_default_($request->object_id, 0);
        if(_empty_($object_id)){
            return $this->fail(200001);
        }
        $settings = WxUserSetting::where('user_id', $object_id)->first();
        $contact = WxUserContactApply::where('user_id', $uid)->where('object_id', $object_id)->first();
        if($contact){
            if($contact->status == 1){
                if($contact->is_wechat_account == 1){
                    $contact->wechat_account = WxUser::where('id', $contact->object_id)->value('wechat_account');
                    if($contact->wechat_account){
                        $contact->wechat_account_safe = str_repeat('*', mb_strlen($contact->wechat_account));
                    }else{
                        $contact->wechat_account_safe = '***';
                    }
                }
                if($contact->is_phone){
                    $contact->phone = _get_origin_attribute('wx_user', [['id', '=', $contact->object_id]], 'phone');
                    if($contact->phone){
                        $contact->phone_safe = str_repeat('*', mb_strlen($contact->phone));
                    }else{
                        $contact->phone_safe = '***';
                    }
                }
            }
            return $this->success($contact);
        }else{

        }
        return $this->fail(200003);
    }

    public function mplogin(Request $request)
    {
        $app_login_style = Utils::get_login_styles();
        if(!in_array(0, $app_login_style)){
            return $this->fail(200008, [], '平台暂未开启微信登录方式');
        }

        $unique = $request->unique;
        $user_id =  Cache::get('mini:mplogin:unique:' . $unique);
        if($user_id){
            Cache::forget('mini:mplogin:unique:' . $unique);

            $login_user = WxUser::find($user_id);
            // 超级管理员
            if($login_user->is_official){
                if(UserUtils::is_mini_supder_admin($login_user->id)){
                    $login_user->is_official = 2;
                }
            }
            UserUtils::user_expend($login_user, true, true, true, true, 5);
            $time = time();
            $login_user->timeStamp = $time;
            // 生成token
            return $this->success(['token' => JwtAuth::getToken('uid', $login_user['id'], $time), 'user'=>$login_user]);
        }else if($user_id == -2){
            return $this->fail(200008, [], '平台未开启微信注册新用户，请您换其他方式先注册账号');
        }else if($user_id == -3){
            return $this->fail(200000, [], '您的账号已在系统黑名单，无法登录，客服qq：'.Settings::get('about_qq', '863627472'));
        }
        return $this->fail(200003);
    }

    public function scan(Request $request){
        if($request->isMethod('GET')){
            $weapp = new WeApp();
            //从‘小程序’获取一个‘二维码’单例对象
            $qrcode = $weapp->getQRCode();
            $scene = uniqid();
//        $page = 'pages/login/login';
            $page = 'pages/pc-login/index';
            //2.获取小程序B码
            $qrcodeContent = $qrcode->getQRCodeB($scene, $page, 430, false, $line_color = null);
            $filePath = 'qrcode/' . $scene . '.png';
            $res = Storage::disk('public')->put($filePath, $qrcodeContent);
            if ($res) {
                return $this->success(['url'=>Storage::url($filePath), 'scene'=>$scene]);
            }else{
                return $this->fail(200006, [], '二维码生成失败');
            }
        }else{

            $token = Cache::get('login:scene:'.$request->scene);
            if($token){
                $user_id = JwtAuth::getUserId($token, 'uid');
                if($user_id > 0){
                    $login_user = WxUser::where('id', $user_id)->first(FieldUtils::userInfoColums());
                    // 超级管理员
                    if($login_user->is_official){
                        if(UserUtils::is_mini_supder_admin($login_user->id)){
                            $login_user->is_official = 2;
                        }
                    }
                    //  支付密码
                    UserUtils::user_expend($login_user, true, true, true, true, 5);
                    $time = time();
                    $login_user->timeStamp = $time;
                    $data = [
                        'token' => $token,
                        'scene' => $request->scene,
                        'user'=>$login_user
                    ];
                    Cache::forget('login:scene:'.$request->scene);
                    return $this->success($data);
                }
                return $this->fail(200000);
            }
            return $this->fail(200000);
        }
    }

    /**
     * @param Request $request
     * @param code
     * @param encryptedData
     * @param iv
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function login(Request $request)
    {
        $app_login_style = Utils::get_login_styles();
        if(_empty_($app_login_style)){
            $app_login_style = [0];
        }
        $code = $request->code;
        $fromUser = $request->header('fromUser',0);
        if(_empty_($fromUser)){
            $fromUser = 0;
        }else if(is_string($fromUser) && StrUtils::startsWith($fromUser, 'itc')){
            $fromUser = trim($fromUser);
        }else if((int)$fromUser > 0){
            if(UserUtils::get_user_state($fromUser) != 0){
                $fromUser = 0;
            }else{
                $fromUser = (int)$fromUser;
            }
        }else{
            $fromUser = 0;
        }
        //例如，在laravel,文件缓存路径为storage_path('cache/')
        $weapp = new WeApp();
        //code 换取 session_key
        $sessionKey = $weapp->getSessionKey($code);
        $sessionKey = json_decode($sessionKey, true);
        if(_empty_($sessionKey) || _empty_(_array_key($sessionKey, 'session_key', null))){
            _logger_(__file__, __line__, $sessionKey);
            return $this->fail(503001);
        }

        // {"session_key":"IVEMC\/Rmlof2WIft0vyJfQ==","openid":"oKIZi5O-FIqbnUlAb15LOGhh6Ix0","unionid":"oep525m2kvV3uvwsP4L-o8qPzUZk"}
        if (_array_key($sessionKey, 'unionid', '') || _array_key($sessionKey, 'openid', '')) {
            $data['unionId'] = _array_key($sessionKey, 'unionid', null);
            $data['openId'] = _array_key($sessionKey, 'openid', '');
            $data['nickName'] = Settings::get('default_user_name', '微信用户');
            $data['avatarUrl'] = Settings::get('img_default_avatar', '');
            $data['province'] = '';
            $data['country'] = '';
            $data['gender'] = 0;
            $data['city'] = '';

            global $__MINI_GLOBAL_CURRENT_USER_ID__;
            if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0 && (!_empty_($data['openId']) || !_empty_($data['unionId']))){
                // 绑定场景，需要截断
                $open_user = WxUser::withTrashed()->where('weixin_openid', $data['openId'])->first();
                $time = time();
                $current_user = WxUser::where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->first(FieldUtils::userInfoColums());
                $is_bind_flag = false;
                if($open_user && $open_user->id > 0){
                    if($open_user->trashed()){
                        WxUser::withTrashed()->where('id', $open_user->id)->forceDelete();
                        if(_empty_($data['unionId'])){
                            try {
                                WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                    'weixin_unionid' => $data['unionId'] ?? null,
                                    'weixin_openid' => $data['openId'] ?? null
                                ]);
                                $is_bind_flag = true;
                            }catch (\Exception $e){
                                $is_bind_flag = false;
                            }
                        }else{

                        }
                    }else if($open_user->id == $__MINI_GLOBAL_CURRENT_USER_ID__){
                        if(_empty_($open_user->weixin_unionid)){
                            try {
                                WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                    'weixin_unionid' => $data['unionId'] ?? null,
                                    'weixin_openid' => $data['openId'] ?? null
                                ]);
                                $is_bind_flag = true;
                            }catch (\Exception $e){
                                $is_bind_flag = false;
                            }

                        }else{
                            WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                'weixin_openid' => $data['openId'] ?? null
                            ]);
                            $is_bind_flag = true;
                        }
                    }else{
                        return $this->fail(503001, [], '您的微信已经绑定了其他账号, 账号UID为：'.$open_user->id);
                    }
                }

                if(!$is_bind_flag){
                    $union_user = WxUser::withTrashed()->where('weixin_unionid', $data['unionId'])->first();
                    if($union_user && $union_user->id > 0){
                        if($union_user->trashed()){
                            if($__MINI_GLOBAL_CURRENT_USER_ID__ != $union_user->id){
                                WxUser::withTrashed()->where('id', $union_user->id)->forceDelete();
                                WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                    'weixin_unionid' => $data['unionId'] ?? null,
                                    'weixin_openid' => $data['openId'] ?? null
                                ]);
                                $is_bind_flag = true;
                            }else{
                                return $this->fail(503001, [], '您的账号非正常状态');
                            }
                        }else{
                            if($union_user->id == $__MINI_GLOBAL_CURRENT_USER_ID__){
                                WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                    'weixin_openid' => $data['openId'] ?? null
                                ]);
                                $is_bind_flag = true;
                            }else{
                                if($data['openId']){
                                    WxUser::withTrashed()->where('id', $union_user->id)->update([
                                        'weixin_openid' => $data['openId'] ?? null
                                    ]);
                                    $is_bind_flag = true;
                                }
                                return $this->fail(503001, [], '您的微信已经绑定了其他账号, 账号UID为：'.$union_user->id);
                            }
                        }
                    }else{
                        WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                            'weixin_unionid' => $data['unionId'] ?? null,
                            'weixin_openid' => $data['openId'] ?? null
                        ]);
                    }
                }

                return $this->success(['token' => JwtAuth::getToken('uid', $current_user->id, $time), 'user'=>$current_user, 'select' => 0], 200, '绑定成功');
            }

            $wxUserModel = new WxUser();
            $user_id = $wxUserModel->registerUser($data, 'mini', $fromUser);
            if($user_id > 0){
                $login_user = WxUser::where('id', $user_id)->first(FieldUtils::userInfoColums());
                // 超级管理员
                if($login_user->is_official){
                    if(UserUtils::is_mini_supder_admin($login_user->id)){
                        $login_user->is_official = 2;
                    }
                }
                //  支付密码
                UserUtils::user_expend($login_user, true, true, true, true, 5);
                $time = time();
                $login_user->timeStamp = $time;

                $select = 0;
                if(mb_strlen( str_replace( [Settings::get('default_user_name', '微信用户'), '微信用户', '普通用户'], '', $login_user->user_name )) != mb_strlen($login_user->user_name)){
                    $select = 1;
                }

                // 生成token
                return $this->success(['token' => JwtAuth::getToken('uid', $login_user['id'], $time), 'user'=>$login_user, 'select' => $select]);
            }else if($user_id == -1){
                return $this->fail(700001);
            }else if($user_id == -2){
                return $this->fail(200008, [], '平台未开启微信注册新用户，请您换其他方式先注册账号');
            }else if($user_id == -3){
                return $this->fail(200000, [], '您的账号已在系统黑名单，无法登录，客服qq：'.Settings::get('about_qq', '863627472'));
            }
        } else {
            return $this->fail(503001);
        }
    }

    /** 请求发送邮箱验证码-已登录用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function user_email_send(Request $request){
        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }
        $uid = $request->uid;
        $email = _empty_default_($request->email, '');
        $template = _empty_default_($request->template, 'text');
        $action = _empty_default_($request->action, 'code');
        if(_empty_($email)){
            return $this->fail(200001);
        }
        if(strpos($email, '@') < 2){
            return $this->fail(200004, [], '请输入合法的邮箱');
        }
        if($action == 'code'){
            $code = mini_rand(1000, 9999);
            $cache_key = md5($uid.':code:60:'.$email);
            if($template == 'text'){
                Mail::to($email)->send(new text('验证码', '你的验证码为：'.$code.'，若非本人操作，请勿泄露。'));
                Cache::forget($cache_key);
                Cache::put($cache_key, $code, 60);
                return $this->success();
            }
        }

    }

    /** 请求发送验证码-已登录用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function user_phone_send(Request $request){
        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }
        $uid = $request->uid;
        $phone = _get_origin_attribute('wx_user', [['id', '=', $uid]], 'phone');
        $idd = _empty_default_($request->idd, 86);
        if(_empty_($phone)){
            return $this->fail(200004, [], '您还没有绑定手机号');
        }

        if(Cache::has(md5($uid.':code:'.$idd.':'.$phone))){
            return $this->fail(200010, [], '已经给您尝试发过短信啦，请稍后再试');
        }
        if(SiteUtils::is_need_captcha('phone_code')){
            return $this->fail(200045);
        }
        $res = Utils::sendSMS($idd, $phone, mini_rand(1000, 9999), 120, $uid.':code:'.$idd.':'.$phone);
        if(_array_key($res, 'code', 0) == 200){
            return $this->success(['phone'=>$phone, 'idd'=>$idd, 'ttl'=>120]);
        }
        return $this->fail(200006, [], _array_key($res, 'msg', ''));
    }


    /** 请求发送验证码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function user_phone_bind(Request $request){
        $phone = $request->phone;
        $code = $request->code;
        $idd = _empty_default_($request->idd, 86);
        $uid = $request->uid;

        global $__MINI_GLOBAL_IP__;

        if (request()->method() === 'GET') {

            global $__MINI_GLOBAL_PAYCODE_0__;
            if(!$__MINI_GLOBAL_PAYCODE_0__){
                return $this->fail(700000);
            }

            if($idd == 86 && !StrUtils::is_phone_number($phone)){
                return $this->fail(200004, [], '不是合法的手机号');
            }

            $the_user = WxUser::where('phone', $phone)->where('country_code', $idd)->first();
            if($the_user){
                if($the_user->id == $uid){
                    return $this->fail(200004, [], '该手机号您已经绑定过了');
                }else{
                    return $this->fail(200004, [], '该手机号已被其他账号绑定');
                }
            }

            if(Cache::has(md5($uid.':code:'.$idd.':'.$phone))){
                return $this->fail(200010, [], '已经给您尝试发过短信啦，请稍后再试');
            }

            if(SiteUtils::is_need_captcha('phone_code')){
                return $this->fail(200045);
            }
            $res = Utils::sendSMS($idd,$phone, mini_rand(1000, 9999), 60, $uid.':code:'.$idd.':'.$phone);
            if(_array_key($res, 'code', 0) == 200){
                return $this->success(['phone'=>$phone, 'idd'=>$idd, 'ttl'=>60]);
            }
            return $this->fail(200006, [], _array_key($res, 'msg', ''));
        }else if (request()->method() === 'POST') {
            $phone = $request->phone;

            $the_user = WxUser::where('phone', $phone)->where('country_code', $idd)->first();
            if($the_user){
                if($the_user->id == $uid){
                    return $this->fail(200004, [], '该手机号您已经绑定过了');
                }else{
                    return $this->fail(200004, [], '该手机号已被其他账号绑定');
                }
            }

            if(_empty_($phone) || _empty_($code)){
                return $this->fail(200001, [], '请输入验证码');
            }
            if($idd == 86 && !StrUtils::is_phone_number($phone)){
                return $this->fail(200004, [], '不是合法的手机号');
            }

            if(strlen($code) !== 4){
                return $this->fail(200004, [], '系统验证码位数不合法');
            }

            $cache_code = Cache::get(md5($uid.':code:'.$idd.':'.$phone), '');
            if(_empty_($cache_code)){
                return $this->fail(200004, [], '验证码已过期');
            }

            if($cache_code != $code){
                return $this->fail(200004, [], '验证码错误');
            }

            $r = WxUser::where('id', $uid)->update(['phone'=>$phone, 'country_code'=>$idd]);
            Cache::forget('get:cached:user:'.$uid);

            return $this->success(['phone'=>$phone]);
        }
    }

    /** 请求发送验证码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function phone_code(Request $request){
        $phone = $request->phone;
        $idd = _empty_default_($request->idd, 86);

        global $__MINI_GLOBAL_PAYCODE_0__,$__MINI_GLOBAL_IP__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }

        $app_login_style = Utils::get_login_styles();
        if($app_login_style){
            if(!in_array(2, $app_login_style)){
                return $this->fail(200008, [], '平台暂未开启手机号登录方式');
            }
        }


        if(_empty_($phone)){
            return $this->fail(200001);
        }
        if($idd == 86 && !StrUtils::is_phone_number($phone)){
            return $this->fail(200004, [], '不是合法的手机号');
        }

        if(Cache::has(md5('code:'.$idd.':'.$phone))){
            return $this->fail(200010, [], '已经给您尝试发过短信啦，请稍后再试');
        }

        if(SiteUtils::is_need_captcha('phone_code')){
            return $this->fail(200045);
        }

        if($phone == '18345678910'){
            return $this->success(['phone'=>$phone, 'idd'=>$idd, 'ttl'=>60]);
        }

        $res = Utils::sendSMS($idd,$phone, mini_rand(1000, 9999), 60, 'code:'.$idd.':'.$phone);
        if(_array_key($res, 'code', 0) == 200){
            return $this->success(['phone'=>$phone, 'idd'=>$idd, 'ttl'=>60]);
        }
        return $this->fail(200006, [], _array_key($res, 'msg', ''));
    }

    /** 验证码登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function phone_login(Request $request){
        $phone = $request->phone;
        $code = $request->code;
        $idd = _empty_default_($request->idd, 86);

        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }

        $app_login_style = Utils::get_login_styles();
        if(!in_array(2, $app_login_style)){
            return $this->fail(200008, [], '平台暂未开启手机号登录方式');
        }
        if(_empty_($phone) || _empty_($code)){
            return $this->fail(200001, [], '请输入验证码');
        }
        if($idd == 86 && !StrUtils::is_phone_number($phone)){
            return $this->fail(200004, [], '不是合法的手机号');
        }

        if(strlen($code) !== 4){
            return $this->fail(200004, [], '系统验证码位数不合法');
        }

        if($phone == '18345678910'){
            if($code != '1234'){
                return $this->fail(200000, [], '请输入验证码：1234');
            }
        }else{
            $cache_code = Cache::get(md5('code:'.$idd.':'.$phone), '');
            if(_empty_($cache_code)){
                return $this->fail(200004, [], '验证码已过期');
            }

            if($cache_code != $code){
                return $this->fail(200004, [], '验证码错误');
            }
        }


        $fromUser = $request->header('fromUser',0);
        if(_empty_($fromUser)){
            $fromUser = 0;
        }else if(is_string($fromUser) && StrUtils::startsWith($fromUser, 'itc')){
            $fromUser = trim($fromUser);
        }else if((int)$fromUser > 0){
            if(UserUtils::get_user_state($fromUser) != 0){
                $fromUser = 0;
            }else{
                $fromUser = (int)$fromUser;
            }
        }else{
            $fromUser = 0;
        }

        $headimgurl = UserUtils::generate_text_avatar($idd);

        $data = [
            'phone' => $phone, 'country_code' => $idd,
            'openId'=>null, 'avatarUrl'=>$headimgurl, 'city'=>'', 'country'=>'',
            'province'=>'', 'language'=>'','nickName'=>Settings::get('default_user_name', '普通用户'),
            'gender'=>0, 'unionId'=>null
        ];

        $wxUserModel = new WxUser();
        $user_id = $wxUserModel->registerUser($data, 'sms', $fromUser);
        if($user_id > 0){
            Cache::forget(md5('code:'.$idd.':'.$phone));
            $login_user = WxUser::where('id', $user_id)->first(FieldUtils::userInfoColums());
            // 超级管理员
            if($login_user->is_official){
                if(UserUtils::is_mini_supder_admin($login_user->id)){
                    $login_user->is_official = 2;
                }
            }
            UserUtils::user_expend($login_user, true, true, true, true, 5);
            $time = time();
            $login_user->timeStamp = $time;
            // 生成token
            return $this->success(['token' => JwtAuth::getToken('uid', $login_user->id, $time), 'user'=>$login_user]);
        }else if($user_id == -1){
            return $this->fail(700001);
        }else if($user_id == -2){
            return $this->fail(200008, [], '平台未开启手机号注册新用户，请您换其他方式先注册账号');
        }else if($user_id == -3){
            return $this->fail(200000, [], '您的账号已在系统黑名单，无法登录，客服qq：'.Settings::get('about_qq', '863627472'));
        }
        return $this->fail(200003);

    }



    public function phone(Request $request)
    {
        $uid = $request->uid;
        $device = $request->header('device','');
        if($device == 'mp'){
            $encryptedData = $request->encryptedData;
            $iv = $request->iv;
            $code = $request->code;

            $weapp = new WeApp();
            //code 换取 session_key
            $sessionKey = $weapp->getSessionKey($code);
            $sessionKey = json_decode($sessionKey, true);
            if(_empty_($sessionKey) || _empty_(_array_key($sessionKey, 'session_key', null))){
                return $this->fail(503001);
            }
            $pc = new WXBizDataCrypt(Settings::get('app_id'), $sessionKey['session_key']);
            $errCode = $pc->decryptData($encryptedData, $iv, $data);
            if ($errCode == 0) {
                $data = json_decode($data, true);
                if($data && $data['purePhoneNumber']){
                    $exixts_id = WxUser::where([ ['phone', '=', $data['purePhoneNumber']], ['country_code', '=', (_empty_($data['countryCode']) ? 86 : $data['countryCode']) ] ])->value('id');
                    if($exixts_id){
                        if($exixts_id == $uid){
//                            $this->fail(200010, [], '您的手机号和新获取的手机号一致，无需更改');
                            return $this->success(['phone'=>substr($data['purePhoneNumber'], 0, 3).'********', 'tip'=>'您的手机号和新获取的手机号一致，无需更改']);
                        }else{
//                          $this->fail(200010, [], '该手机号已绑定');
                            WxUser::where('id', $exixts_id)->update(['phone'=>'', 'country_code'=>null]);
                            if(_empty_($data['countryCode'])){
                                WxUser::where('id', $uid)->update(['phone'=>$data['purePhoneNumber'], 'country_code'=>'86']);
                            }else{
                                WxUser::where('id', $uid)->update(['phone'=>$data['purePhoneNumber'], 'country_code' => $data['countryCode']]);
                            }
                            return $this->success(['phone'=>substr($data['purePhoneNumber'], 0, 3).'********', 'tip'=>'旧账号已自动解绑，该手机号已绑定至当前账号']);
                        }
                    }else{
                        if(_empty_($data['countryCode'])){
                            WxUser::where('id', $uid)->update(['phone'=>$data['purePhoneNumber'], 'country_code'=>'86']);
                        }else{
                            WxUser::where('id', $uid)->update(['phone'=>$data['purePhoneNumber'], 'country_code' => $data['countryCode']]);
                        }
                        return $this->success(['phone'=>substr($data['purePhoneNumber'], 0, 3).'********', 'tip'=>'绑定成功']);
                    }
                }
            }else{
                return $this->fail(200004, [], '解密出错');
            }
        }
        return $this->fail(200014);

    }

    /** QQ登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginQQ(Request $request){
        if(_empty_($request->openId) && _empty_($request->user)){
            return $this->fail(200001);
        }
        $openId = trim($request->openId);
        if(_empty_($openId)){
            $openId = trim($request->user);
        }
        if(_empty_($openId)){
            return $this->fail(200001);
        }
        $app_login_style = Utils::get_login_styles();
        if(!in_array(3, $app_login_style)){
            return $this->fail(200008, [], '平台暂未开启QQ登录方式');
        }

        $fromUser = $request->header('fromUser',0);
        if(_empty_($fromUser)){
            $fromUser = 0;
        }else if(is_string($fromUser) && StrUtils::startsWith($fromUser, 'itc')){
            $fromUser = trim($fromUser);
        }else if((int)$fromUser > 0){
            if(UserUtils::get_user_state($fromUser) != 0){
                $fromUser = 0;
            }else{
                $fromUser = (int)$fromUser;
            }
        }else{
            $fromUser = 0;
        }

        $unionid = $request->unionid;
        if(_empty_($unionid)){
//            return $this->fail(200008, [], '未获取到unionid');
        }

        $nick_name = $request->nickName;
        if(_empty_($nick_name)){
            $nick_name = 'QQ用户';
        }

        $headimgurl = $request->figureurl_2;
        if(_empty_($headimgurl)){
            $headimgurl = UserUtils::generate_text_avatar(strtoupper('QQ'));
        }

        $gender = 0;
        $gender_tip = $request->gender;
        if($gender_tip == '男'){
            $gender = 1;
        }else if($gender_tip == '女'){
            $gender = 2;
        }


        $data = [
            'openId'=>$openId, 'avatarUrl'=>$headimgurl, 'city'=>'', 'country'=>'',
            'province'=>'', 'language'=>'','nickName'=>$nick_name,
            'gender'=>$gender, 'unionId'=> $unionid
        ];

        global $__MINI_GLOBAL_CURRENT_USER_ID__;
        if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0 && (!_empty_($data['openId']) || !_empty_($data['unionId']))){
            global $__MINI_GLOBAL_DEVICE__;
            if($__MINI_GLOBAL_DEVICE__ == 'app'){
                // 绑定场景，需要截断
                $open_user = WxUser::withTrashed()->where('qq_app_openid', $data['openId'])->first();
                $time = time();
                $current_user = WxUser::where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->first(FieldUtils::userInfoColums());
                $is_bind_flag = false;
                if($open_user && $open_user->id > 0){
                    if($open_user->trashed()){
                        WxUser::withTrashed()->where('id', $open_user->id)->forceDelete();
                        if(_empty_($data['unionId'])){
                            try {
                                WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                    'qq_unionid' => $data['unionId'] ?? null,
                                    'qq_app_openid' => $data['openId'] ?? null
                                ]);
                                $is_bind_flag = true;
                            }catch (\Exception $e){
                                $is_bind_flag = false;
                            }
                        }else{

                        }
                    }else if($open_user->id == $__MINI_GLOBAL_CURRENT_USER_ID__){
                        if(_empty_($open_user->weixin_unionid)){
                            try {
                                WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                    'qq_unionid' => $data['unionId'] ?? null,
                                    'qq_app_openid' => $data['openId'] ?? null
                                ]);
                                $is_bind_flag = true;
                            }catch (\Exception $e){
                                $is_bind_flag = false;
                            }

                        }else{
                            WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                'qq_app_openid' => $data['openId'] ?? null
                            ]);
                            $is_bind_flag = true;
                        }
                    }else{
                        return $this->fail(503001, [], '您的QQ已经绑定了其他账号, 账号UID为：'.$open_user->id);
                    }
                }

                if(!$is_bind_flag){
                    $union_user = WxUser::withTrashed()->where('qq_unionid', $data['unionId'])->first();
                    if($union_user && $union_user->id > 0){
                        if($union_user->trashed()){
                            if($__MINI_GLOBAL_CURRENT_USER_ID__ != $union_user->id){
                                WxUser::withTrashed()->where('id', $union_user->id)->forceDelete();
                                WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                    'qq_unionid' => $data['unionId'] ?? null,
                                    'qq_app_openid' => $data['openId'] ?? null
                                ]);
                                $is_bind_flag = true;
                            }else{
                                return $this->fail(503001, [], '您的账号非正常状态');
                            }
                        }else{
                            if($union_user->id == $__MINI_GLOBAL_CURRENT_USER_ID__){
                                WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                    'qq_app_openid' => $data['openId'] ?? null
                                ]);
                                $is_bind_flag = true;
                            }else{
                                if($data['openId']){
                                    WxUser::withTrashed()->where('id', $union_user->id)->update([
                                        'qq_app_openid' => $data['openId'] ?? null
                                    ]);
                                    $is_bind_flag = true;
                                }
                                return $this->fail(503001, [], '您的QQ已经绑定了其他账号, 账号UID为：'.$union_user->id);
                            }
                        }
                    }else{
                        WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                            'qq_unionid' => $data['unionId'] ?? null,
                            'qq_app_openid' => $data['openId'] ?? null
                        ]);
                    }
                }

                return $this->success(['token' => JwtAuth::getToken('uid', $current_user->id, $time), 'user'=>$current_user, 'select' => 0], 200, '绑定成功');
            }

        }

        $wxUserModel = new WxUser();
        $user_id = $wxUserModel->registerUser($data, 'qq-app', $fromUser);
        if($user_id > 0){
            $login_user = WxUser::where('id', $user_id)->first(FieldUtils::userInfoColums());
            // 超级管理员
            if($login_user->is_official){
                if(UserUtils::is_mini_supder_admin($login_user->id)){
                    $login_user->is_official = 2;
                }
            }
            UserUtils::user_expend($login_user, true, true, true, true, 5);
            $time = time();
            $login_user->timeStamp = $time;
            // 生成token
            return $this->success(['token' => JwtAuth::getToken('uid', $login_user->id, $time), 'user'=>$login_user]);
        }else if($user_id == -1){
            return $this->fail(700001);
        }else if($user_id == -2){
            return $this->fail(200008, [], '平台未开启QQ注册新用户，请您换其他方式先注册账号');
        }else if($user_id == -3){
            return $this->fail(200000, [], '您的账号已在系统黑名单，无法登录，客服qq：'.Settings::get('about_qq', '863627472'));
        }
        return $this->fail(200003);
    }


    /** loginApple
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginApple(Request $request){
        if(_empty_($request->openId) && _empty_($request->user)){
            return $this->fail(200001);
        }
        $openId = trim($request->openId);
        if(_empty_($openId)){
            $openId = trim($request->user);
        }
        if(_empty_($openId)){
            return $this->fail(200001);
        }
        $app_login_style = Utils::get_login_styles();
        if(!in_array(1, $app_login_style)){
            return $this->fail(200008, [], '平台暂未开启苹果登录方式');
        }
        $realUserStatus = $request->realUserStatus;
        if($realUserStatus != 2){
//            return $this->fail(200001, [], '该apple账号疑似不是真实的人');
        }

        $fromUser = $request->header('fromUser',0);
        if(_empty_($fromUser)){
            $fromUser = 0;
        }else if(is_string($fromUser) && StrUtils::startsWith($fromUser, 'itc')){
            $fromUser = trim($fromUser);
        }else if((int)$fromUser > 0){
            if(UserUtils::get_user_state($fromUser) != 0){
                $fromUser = 0;
            }else{
                $fromUser = (int)$fromUser;
            }
        }else{
            $fromUser = 0;
        }

        $email = $request->email;
        if(_empty_($email)){
            $email = null;
        }

        $nick_name = '';
        $fullName = $request->fullName;
        if($fullName && _array_key($fullName, 'familyName', '') && _array_key($fullName, 'giveName', '')){
            $nick_name .= $fullName['familyName'];
            $nick_name .= $fullName['giveName'];
        }

        if(_empty_($nick_name)){
            $nick_name = 'ios用户';
        }

        $headimgurl = '';
        if($nick_name == 'ios用户'){
            $headimgurl = Settings::get('img_default_avatar', 'https://img.mini.minisns.cn/2022/11/16/cf994299ccb183f26b2417ea642dd6aa.png');
        }else{
            $chars = '';
            $familyName = _array_key($fullName, 'familyName', '');
            $giveName = _array_key($fullName, 'giveName', '');

            if(StrUtils::is_contain_chinese($familyName.$giveName)){
                if(mb_strlen($familyName) + mb_strlen($giveName) == 2){
                    $_array = Pinyin::abbr($familyName.$giveName)->toArray();
                    if($_array && count($_array) == 2){
                        $chars = $_array[0].$_array[1];
                    }
                }else if(mb_strlen($giveName) == 2){
                    $_array = Pinyin::abbr($giveName)->toArray();
                    if($_array && count($_array) == 2){
                        $chars = $_array[0].$_array[1];
                    }
                }else{
                    if($familyName){
                        $_array = Pinyin::abbr($familyName)->toArray();
                        if($_array){
                            $chars = $_array[0];
                        }
                    }
                    if(_empty_($chars) && $giveName){
                        $_array = Pinyin::abbr($giveName)->toArray();
                        if($_array){
                            $chars = $_array[0];
                        }
                    }
                }
            }else{
                if($familyName){
                    $chars .= mb_substr($familyName, 0, 1);
                }
                if($giveName){
                    $chars .= mb_substr($giveName, 0, 1);
                }
            }


            if($chars){
                $headimgurl = UserUtils::generate_text_avatar(strtoupper($chars));
            }

            if(_empty_($headimgurl)){
                $headimgurl = Settings::get('img_default_avatar', 'https://img.mini.minisns.cn/2022/11/16/cf994299ccb183f26b2417ea642dd6aa.png');
            }
        }

        $data = [
            'openId'=>$openId, 'avatarUrl'=>$headimgurl, 'city'=>'', 'country'=>'',
            'province'=>'', 'language'=>'','nickName'=>$nick_name,
            'gender'=>0, 'unionId'=>null
        ];

        $wxUserModel = new WxUser();
        $user_id = $wxUserModel->registerUser($data, 'apple', $fromUser);
        if($user_id > 0){
            $login_user = WxUser::where('id', $user_id)->first(FieldUtils::userInfoColums());
            // 超级管理员
            if($login_user->is_official){
                if(UserUtils::is_mini_supder_admin($login_user->id)){
                    $login_user->is_official = 2;
                }
            }
            UserUtils::user_expend($login_user, true, true, true, true, 5);
            $time = time();
            $login_user->timeStamp = $time;
            // 生成token
            return $this->success(['token' => JwtAuth::getToken('uid', $login_user->id, $time), 'user'=>$login_user]);
        }else if($user_id == -1){
            return $this->fail(700001);
        }else if($user_id == -2){
            return $this->fail(200008, [], '平台未开启Apple注册新用户，请您换其他方式先注册账号');
        }else if($user_id == -3){
            return $this->fail(200000, [], '您的账号已在系统黑名单，无法登录，客服qq：'.Settings::get('about_qq', '863627472'));
        }
        return $this->fail(200003);


    }

    /** app端微信code登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginAppCode(Request $request){
        $app_login_style = Utils::get_login_styles();
        if(!in_array(0, $app_login_style)){
            return $this->fail(200008, [], '平台暂未开启苹果登录方式');
        }

        if(_empty_($request->code)){
            return $this->fail(500001, ['msg'=>'code参数为空'], 'code参数为空');
        }
        $driver = Socialite::driver('weixin');
        $fromUser = $request->header('fromUser',0);
        if(_empty_($fromUser)){
            $fromUser = 0;
        }else if(is_string($fromUser) && StrUtils::startsWith($fromUser, 'itc')){
            $fromUser = trim($fromUser);
        }else if((int)$fromUser > 0){
            if(UserUtils::get_user_state($fromUser) != 0){
                $fromUser = 0;
            }else{
                $fromUser = (int)$fromUser;
            }
        }else{
            $fromUser = 0;
        }

        $response = $driver->getAccessTokenResponse($request->code);
        $errcode = _array_key($response, 'errcode', '');
        if( $errcode || !isset($response['openid']) || !isset($response['access_token'])){
            return $this->fail(500001, ['errcode'=>$errcode, 'errmsg'=>_array_key($response, 'errmsg', '')], _array_key($response, 'errmsg', '').'_1');
        }
        $driver->setOpenId($response['openid']);
        $oauthUser = $driver->userFromToken($response['access_token']);

        $errcode2 = _array_key($oauthUser, 'errcode', '');
        if( $errcode2 || !isset($oauthUser['openid'])){
            return $this->fail(500001, ['errcode'=>$errcode2, 'errmsg'=>_array_key($oauthUser, 'errmsg', '')], _array_key($oauthUser, 'errmsg', '').'_2');
        }

        $openId = $oauthUser['openid'];
        $unionId = $oauthUser['unionid'];
        if(_empty_($openId) && _empty_($unionId)){
            return $this->fail(503001);
        }
        $data = [
            'openId'=>$openId, 'avatarUrl'=>$oauthUser['headimgurl'] ?: '', 'city'=>$oauthUser['city'] ?: '', 'country'=>$oauthUser['country'] ?: '',
            'province'=>$oauthUser['province'] ?: '', 'language'=>'','nickName'=>$oauthUser['nickname'] ?: '',
            'gender'=>$oauthUser['sex'] ?: 0, 'unionId'=>$unionId
        ];


        global $__MINI_GLOBAL_CURRENT_USER_ID__;
        if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0 && (!_empty_($data['openId']) || !_empty_($data['unionId']))){
            // 绑定场景，需要截断
            $open_user = WxUser::withTrashed()->where('weixin_openid', $data['openId'])->first();
            $time = time();
            $current_user = WxUser::where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->first(FieldUtils::userInfoColums());
            $is_bind_flag = false;
            if($open_user && $open_user->id > 0){
                if($open_user->trashed()){
                    WxUser::withTrashed()->where('id', $open_user->id)->forceDelete();
                    if(_empty_($data['unionId'])){
                        try {
                            WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                'weixin_unionid' => $data['unionId'] ?? null,
                                'weixin_openid' => $data['openId'] ?? null
                            ]);
                            $is_bind_flag = true;
                        }catch (\Exception $e){
                            $is_bind_flag = false;
                        }
                    }else{

                    }
                }else if($open_user->id == $__MINI_GLOBAL_CURRENT_USER_ID__){
                    if(_empty_($open_user->weixin_unionid)){
                        try {
                            WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                'weixin_unionid' => $data['unionId'] ?? null,
                                'weixin_openid' => $data['openId'] ?? null
                            ]);
                            $is_bind_flag = true;
                        }catch (\Exception $e){
                            $is_bind_flag = false;
                        }

                    }else{
                        WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                            'weixin_openid' => $data['openId'] ?? null
                        ]);
                        $is_bind_flag = true;
                    }
                }else{
                    return $this->fail(503001, [], '您的微信已经绑定了其他账号, 账号UID为：'.$open_user->id);
                }
            }

            if(!$is_bind_flag){
                $union_user = WxUser::withTrashed()->where('weixin_unionid', $data['unionId'])->first();
                if($union_user && $union_user->id > 0){
                    if($union_user->trashed()){
                        if($__MINI_GLOBAL_CURRENT_USER_ID__ != $union_user->id){
                            WxUser::withTrashed()->where('id', $union_user->id)->forceDelete();
                            WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                'weixin_unionid' => $data['unionId'] ?? null,
                                'weixin_openid' => $data['openId'] ?? null
                            ]);
                            $is_bind_flag = true;
                        }else{
                            return $this->fail(503001, [], '您的账号非正常状态');
                        }
                    }else{
                        if($union_user->id == $__MINI_GLOBAL_CURRENT_USER_ID__){
                            WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                                'weixin_openid' => $data['openId'] ?? null
                            ]);
                            $is_bind_flag = true;
                        }else{
                            if($data['openId']){
                                WxUser::withTrashed()->where('id', $union_user->id)->update([
                                    'weixin_openid' => $data['openId'] ?? null
                                ]);
                                $is_bind_flag = true;
                            }
                            return $this->fail(503001, [], '您的微信已经绑定了其他账号, 账号UID为：'.$union_user->id);
                        }
                    }
                }else{
                    WxUser::withTrashed()->where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->update([
                        'weixin_unionid' => $data['unionId'] ?? null,
                        'weixin_openid' => $data['openId'] ?? null
                    ]);
                }
            }

            return $this->success(['token' => JwtAuth::getToken('uid', $current_user->id, $time), 'user'=>$current_user, 'select' => 0], 200, '绑定成功');
        }

        $wxUserModel = new WxUser();
        $user_id = $wxUserModel->registerUser($data, 'app', $fromUser);
        if($user_id > 0){
            $login_user = WxUser::where('id', $user_id)->first(FieldUtils::userInfoColums());
            // 超级管理员
            if($login_user->is_official){
                if(UserUtils::is_mini_supder_admin($login_user->id)){
                    $login_user->is_official = 2;
                }
            }
            UserUtils::user_expend($login_user, true, true, true, true, 5);
            $time = time();
            $login_user->timeStamp = $time;
            // 生成token
            return $this->success(['token' => JwtAuth::getToken('uid', $login_user->id, $time), 'user'=>$login_user]);
        }else if($user_id == -1){
            return $this->fail(700001);
        }else if($user_id == -2){
            return $this->fail(200008, [], '平台未开启微信注册新用户，请您换其他方式先注册账号');
        }else if($user_id == -3){
            return $this->fail(200000, [], '您的账号已在系统黑名单，无法登录，客服qq：'.Settings::get('about_qq', '863627472'));
        }
        return $this->fail(200003);
    }

    /** 账号注销申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function logoff(Request $request){

        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }

        $uid = $request->uid;
        UserUtils::add_user_notice(4001, $uid, '账号处于注销中状态', '您于'.current_time().'开始申请注销账号，当前账号将会被标记为[非正常状态]', 100);
        WxUser::where('id', $uid)->update( ['user_state'=>1] );
        WxPost::where('user_id', $uid)->update(['posts_state' => 2]);
        Cache::forget('user:state:'.$uid);
        return $this->success();
    }


    public function contactApply(Request &$request)
    {
        $object_id = _empty_default_($request->object_id, 0);
        if(_empty_($object_id)){
            return $this->fail(200001);
        }
        $is_phone = _empty_default_($request->is_phone, 0) == 1 ? 1 : 0;
        $is_wechat_account = _empty_default_($request->is_wechat_account, 0) == 1 ? 1 : 0;
        $reason = _empty_default_($request->reason, '');
        if(_empty_($reason)){
            return $this->fail(200004, [], '请先输入申请理由');
        }

        DB::beginTransaction();
        try {
            // todo:
            $uid = $request->uid;
            $model = new WxUserContactApply();
            $model->user_id = $uid;
            $model->object_id = $object_id;
            $model->is_phone = $is_phone;
            $model->is_wechat_account = $is_wechat_account;
            $model->reason = $reason;
            $model->status = 0;
            $r = $model->save();
            if($r){
                $r2 = WxContRepositories::add($model->user_id, $model->object_id, null, null, null, 0, null, null, $model->id);
                if($r2){
                    DB::commit();
                    return $this->success();
                }else{
                    DB::rollBack();
                    return $this->fail(200002);
                }
            }else{
                DB::rollBack();
                return $this->fail(200002);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200006);
        }
    }


    /**
     * 获取用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userInfo(Request $request)
    {
        $uid = $request->uid;
        $player = $request->player;
        $cid = _empty_default_($request->cid, '');
        $third_account = _empty_default_($request->account, 0);

        $is_access_token = false;
        if(!_empty_($request->get('access_token')) && !_empty_(Settings::get('mini_access_token', ''))){
            if($request->get('access_token') == Settings::get('mini_access_token', '')){
                $is_access_token = true;
            }
        }

        if($third_account == 1){
            // 获取第三方账号绑定信息
            $data = WxUser::where('id', $uid)->first(['id', 'weixin_openid', 'weixin_unionid', 'weixin_app_openid', 'weixin_mp_openid', 'weixin_web_openid', 'weixin_shop_openid', 'qq_unionid', 'qq_app_openid', 'qq_web_openid']);
            if($data){
                return $this->success($data);
            }else{
                return $this->fail(200003);
            }
        }


        $info = (new WxUserRepositores())->info($uid);
        if($info){
            if($player){
                $info->is_played = true;
            }else{
                $info->is_played = false;
            }

            if($info->is_official){
                if(UserUtils::is_mini_supder_admin($info->id)){
                    $info->is_official = 2;
                }
            }
            UserUtils::user_expend($info, true, true, true, true,5);

            if($is_access_token){
                $info->origin_phone = _get_origin_attribute('wx_user', [['id', '=', $info->id]], 'phone');
            }


            if(!_empty_($cid) && $info->push_client_id != $cid){
                WxUser::withoutSyncingToSearch(function () use ($info, $cid) {
                    WxUser::where('id', $info->id)->update(['push_client_id'=>$cid]);
                });
            }

            $info->timeStamp = time();

            if(_empty_($info->user_name)){
                return $this->success($info, 200025);
            }else{
                return $this->success($info);
            }
        }else{
            return $this->fail(200003);
        }
    }

    public function userSystemInfo(Request $request)
    {
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200001);
        }
        $deviceModel = _empty_default_($request->deviceModel, '');
        $system = _empty_default_($request->system, '');
        if(request()->isMethod('POST')){
            UserUtils::set_online($uid, '', $deviceModel, $system);
            return $this->success();
        }
    }


    /**
     * 根据用户id获取基本用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userInfoByUserId(Request $request)
    {
        global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
        $user_id = $request->user_id;
        $uid = $request->uid;
        $scene = $request->header('scene', 0);
        if(_empty_($user_id)){
            return $this->fail(200001);
        }
        if($user_id < 0){
            $data = WxUser::where('id', _abs($user_id))->first(FieldUtils::userInfoColums());
            $longtaps = [];
            if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                $longtaps[] = [
                    'text' => '用户管理',
                    'emoji' => '🥸',
                    'list' => [
                        [
                            'name' => '真实用户',
                            'action' => 'icon',
                            'target_type' => 6,
                            'target_id' => '/pages/user/user?id=' . _abs($user_id),
                        ]
                    ]
                ];
            }

            // 匿名
            return $this->success([
                'id' => -1,
                'user_name' => _empty_default_($data->anonymous_name, '匿名'),
                'user_avatar' => _empty_default_($data->anonymous_avatar, Settings::get('img_default_avatar', '')),
                'longtaps' => $longtaps,
                'followTotal' => 0,
                'fansTotal' => 0,
                'likeTotal' => 0,
                'user_background_maps' => Settings::get('user_background_maps', ''),
                'user_background_color' => _empty_default_(get_site_meta('user_background_color', 's'), '18, 14, 17'),
                'setting' => [
                    'privacy_message_me' => 1,
                    'privacy_collected_post_show' => 1,
                    'privacy_my_follow_show' => 1,
                    'privacy_follow_me_show' => 1,
                    'privacy_get_my_wechat' => 4,
                    'privacy_get_my_wechat_pay' => 0,
                    'privacy_get_my_phone' => 4,
                    'privacy_get_my_phone_pay' => 0,
                    'privacy_personal_recommend' => 1,
                    'privacy_personal_ad' => 1,
                    'privacy_personal_geo_title' => 1,
                    'diy_scene_1_post_list_style' => 1,
                    'diy_scene_6_post_list_style' => 1,
                    'diy_scene_7_post_list_style' => 1,
                    'diy_scene_8_post_list_style' => 1,
                    'teenage_mode_state' => 0,
                ]
            ]);
        }
        $data = WxUser::where('id', $user_id)->first(FieldUtils::userInfoColums());
        if($data){
            $data->append(['ip_address']);
        }else{
            return $this->fail(200003);
        }


        if($__MINI_GLOBAL_IS_ADMIN_SUPER__ && $data->is_robot > 0){
            $data->user_name =  $data->user_name.' 🤖';
        }

        UserUtils::user_expend($data, false, false, true, true,8);

        $data->followTotal = WxUserFollow::where('user_id', $user_id)->count();

        $data->fansTotal = WxUserFollow::where('user_follow_id', $user_id)->count();
        $count1 = WxLike::where('posts_user_id', $user_id)->count();
        $count2 = WxCommentLike::where('comment_user_id', $user_id)->count();
        $data->likeTotal = $count1 + $count2;
        if($uid > 0 && $uid != $user_id){
            $data->isFollow = WxUserFollow::where('user_id', $uid)->where('user_follow_id', $user_id)->exists();
            $data->isFans = WxUserFollow::where('user_id', $user_id)->where('user_follow_id', $uid)->exists();
        }else{
            $data->isFollow = false;
            $data->isFans = false;
        }

        $data->user_background_color = get_user_meta($user_id, 'user_background_color');
        if(_empty_($data->user_background_color)){
            $data->user_background_color = UserUtils::user_bg_color_update($user_id);
            if(_empty_($data->user_background_color)){
                $data->user_background_color = '18, 14, 17';
            }
        }

        $blacked = UserUtils::is_user_blacked_to($uid, $data->id);

        if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
            $data->actions = [
                ['title' => '举报'],
                ['title' => $blacked ? '取消拉黑' : '拉黑'],
                ['title' => 'ta的钱包'],
                ['title'=>'编辑ta的资料']
            ];
        }else{
            $data->actions = [
                ['title' => '举报'],
                ['title' => $blacked ? '取消拉黑' : '拉黑'],
            ];
        }

        if($scene == 50005 || $scene == 50004 || $scene == 50006){
            global $__MINI_GLOBAL_PAYCODE_25__;
            if($__MINI_GLOBAL_PAYCODE_25__){
                $data->pets = [
                    'adoption' => [
                        'count'=>[
                            'status0' => WxPetsAdoption::where('user_id', $user_id)->where('adopt_status', 0)->count(),
                            'status1' => WxPetsAdoption::where('user_id', $user_id)->where('adopt_status', 1)->count(),
                        ]
                    ]
                ];
            }
        }

        if( $uid > 0 ){
            update_user_visit($uid,4, $user_id);
        }

        return $this->success($data);
    }



    /**
     * 更新用户资料
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateInfo(Request $request)
    {
        $uid = $request->uid;
        _limit_user('update:user:info', $uid, 20);

        $data = $request->all();

        $user_id = _array_key($data, 'user_id', 0);
        if($user_id > 0){
            if(UserUtils::is_mini_supder_admin($uid)){
                $uid = $user_id;
            }else{
                return $this->fail(200000, [], '你还不是超级管理员，无法保存别人的资料');
            }
        }
        $old_user = WxUser::find($uid);
        if(_empty_($old_user)){
            return $this->fail(200003);
        }
        $is_user_setting = _array_key($data, 'is_user_setting', false);
        if($is_user_setting){
            $user_setting_update_flag = false;
            if(isset($data['privacy_message_me'])){
                if(!in_array($data['privacy_message_me'], [1, 2, 3, 4])){
                    return $this->fail(200004);
                }
                $r = WxUserSetting::where('user_id', $uid)->update(['privacy_message_me' => $data['privacy_message_me']]);
                if($r){
                    $user_setting_update_flag = true;
                }else{
                    return $this->fail(200002);
                }
            }

            foreach (['wechat', 'phone'] as $wechat_or_phone){
                if(isset($data['privacy_get_my_'.$wechat_or_phone])){
                    if(!in_array($data['privacy_get_my_'.$wechat_or_phone], [1, 2, 3, 4, 5])){
                        return $this->fail(200004);
                    }
                    if(($wechat_or_phone == 'wechat' && _empty_($old_user->wechat_account)) || ($wechat_or_phone == 'phone' && _empty_($old_user->phone))){
                        return $this->fail(200043, [
                            'title' => $wechat_or_phone == 'wechat' ? '未保存微信号' : '未绑定手机号',
                            'content' => '是否前往[编辑资料]进行补充',
                            'confirmText' => '去补充',
                            'target_type' => 6,
                            'target_id' => $wechat_or_phone == 'wechat' ? '/pagesA/mine/editmine/editmine?wechat_account=1' : '/pagesA/mine/editmine/editmine?phone=1'
                        ], $wechat_or_phone == 'wechat' ? '未保存微信号' : '未绑定手机号');
                    }
                    $updates = [
                        'privacy_get_my_'.$wechat_or_phone => $data['privacy_get_my_'.$wechat_or_phone]
                    ];
                    if($data['privacy_get_my_'.$wechat_or_phone] == 5 && WxUserSetting::where('user_id', $uid)->value('privacy_get_my_'.$wechat_or_phone.'_pay') < 1){
                        $updates['privacy_get_my_'.$wechat_or_phone.'_pay'] = 1;
                    }
                    $r = WxUserSetting::where('user_id', $uid)->update($updates);
                    if($r){
                        $user_setting_update_flag = true;
                    }else{
                        return $this->fail(200002);
                    }
                }
                if(isset($data['privacy_get_my_'.$wechat_or_phone.'_pay'])){
                    $data['privacy_get_my_'.$wechat_or_phone.'_pay'] = round((float)$data['privacy_get_my_'.$wechat_or_phone.'_pay'], 2);
                    if($data['privacy_get_my_'.$wechat_or_phone.'_pay'] < 1){
                        return $this->fail(200004, [], '付费数额不能小于1元');
                    }
                    $r = WxUserSetting::where('user_id', $uid)->update(['privacy_get_my_'.$wechat_or_phone.'_pay' => $data['privacy_get_my_'.$wechat_or_phone.'_pay']]);
                    if($r){
                        $user_setting_update_flag = true;
                    }else{
                        return $this->fail(200002);
                    }
                }
            }

            // 1,2类型
            foreach (['privacy_collected_post_show', 'privacy_my_follow_show', 'privacy_follow_me_show','privacy_personal_recommend_user', 'privacy_personal_recommend', 'privacy_personal_ad', 'privacy_personal_geo_title', 'diy_short_vibrate_feedback'] as $key){
                if(isset($data[$key])){
                    if(!in_array($data[$key], [1, 2])){
                        return $this->fail(200004);
                    }
                    $r = WxUserSetting::where('user_id', $uid)->update([$key => $data[$key]]);
                    if($r){
                        $user_setting_update_flag = true;
                    }else{
                        return $this->fail(200002);
                    }
                }
            }

            // 2,3类型
            foreach (['diy_scene_1_post_list_style', 'diy_scene_6_post_list_style', 'diy_scene_7_post_list_style','diy_scene_8_post_list_style'] as $key){
                if(isset($data[$key])){
                    if(!in_array($data[$key], [2, 3])){
                        return $this->fail(200004);
                    }
                    $r = WxUserSetting::where('user_id', $uid)->update([$key => $data[$key]]);
                    if($r){
                        $user_setting_update_flag = true;
                    }else{
                        return $this->fail(200002);
                    }
                }
            }

            // 字符串类型
            foreach (['social_sph_id'] as $key){
                if(!_empty_(_array_key($data, $key, ''))){
                    if($key == 'social_sph_id'){
                        if($data[$key] == 'close'){
                            $data[$key] = '';
                        }else{
                            if(strlen($data[$key]) != 15 || !StrUtils::startsWith($data[$key], 'sph')){
                                return $this->fail(200004, [], '视频号id需要以sph开头的16位字符串');
                            }
                        }
                    }
                    $r = WxUserSetting::where('user_id', $uid)->update([$key => $data[$key]]);
                    if($r){
                        $user_setting_update_flag = true;
                    }else{
                        return $this->fail(200002);
                    }
                }
            }


            if(isset($data['teenage_mode_password'])){
                if(strlen($data['teenage_mode_password']) != 4){
                    return $this->fail(200004);
                }
                $user_setting = WxUserSetting::where('user_id', $uid)->first();
                if($user_setting){
                    $r = false;
                    if($user_setting->teenage_mode_state == 1){
                        // 关闭
                        if($user_setting->teenage_mode_password == $data['teenage_mode_password']){
                            $r = WxUserSetting::where('user_id', $uid)->update(['teenage_mode_password' => '', 'teenage_mode_state' => 2]);
                        }else{
                            return $this->fail(200004, [], '密码错误');
                        }
                    }else{
                        // 打开
                        $r = WxUserSetting::where('user_id', $uid)->update(['teenage_mode_password' => $data['teenage_mode_password'], 'teenage_mode_state' => 1]);
                    }
                    if($r){
                        $user_setting_update_flag = true;
                    }else{
                        return $this->fail(200002);
                    }
                }
            }


            if($user_setting_update_flag){
                Cache::forget('get:cached:user:'.$uid);
                $login_user = WxUser::where('id', $uid)->first(FieldUtils::userInfoColums());
                // 超级管理员
                if($login_user->is_official){
                    if(UserUtils::is_mini_supder_admin($login_user->id)){
                        $login_user->is_official = 2;
                    }
                }
                UserUtils::user_expend($login_user, true, true, true, true, 5);
                $login_user->timeStamp = time();

                return $this->success(['code'=>1, 'user'=>$login_user]);
            }else{
                return $this->fail(200004);
            }
        }

        $data['user_name'] = str_replace([' 🤖', '🤖',' 💙🤖', ' 💗🤖', '💙🤖', '💗🤖'], '', trim(_array_key($data, 'user_name', '')));

        if(_empty_($data['user_name'])){
            return $this->fail(200001);
        }

        if(_empty_(_array_key($data, 'user_avatar', ''))){
            $data['user_avatar'] = '';
        }
        if(_empty_(_array_key($data, 'user_name', ''))){
            $data['user_name'] = '';
        }

        if(_empty_(_array_key($data, 'wechat_account', ''))){
            $data['wechat_account'] = '';
        }

        if(_empty_(_array_key($data, 'user_introduce', '')) || Settings::get('app_user_introduce', '', true) == _array_key($data, 'user_introduce', '') ){
            $data['user_introduce'] = '';
        }
        if(_empty_(_array_key($data, 'user_birthday', '')) || _array_key($data, 'user_birthday', '') == '请选择'){
            $data['user_birthday'] = '';
        }

        if(!StrUtils::is_valid_date(_array_key($data, 'user_birthday', ''), 'Y-m-d')){
            $data['user_birthday'] = '';
        }else{
            if(strtotime(_array_key($data, 'user_birthday', '')) >= time()){
                return $this->fail(200004, [], '生日不合法');
            }
        }

        if(_empty_(_array_key($data, 'user_background_maps', ''))){
            $data['user_background_maps'] = '';
        }

        if(_empty_(_array_key($data, 'gender', 0)) || _array_key($data, 'gender', 0) == '请选择'
            || StrUtils::is_contain_chinese(_array_key($data, 'gender', 0)) || !in_array(_array_key($data, 'gender', 0), [0, 1, 2]) ){
            $data['gender'] = 0;
        }

        $user_labels = _array_key($data, 'user_labels', []);
        if($user_labels){
            if($user_labels == -1){
                $data['user_labels'] = -1;
            }else{
                // 过滤
                $user_labels_ =[];
                $app_user_labels = Settings::get('app_user_labels', [], true);
                foreach ($user_labels as $label){
                    if(in_array($label, $app_user_labels)){
                        $user_labels_[] = $label;
                    }
                }
                $data['user_labels'] = $user_labels_;
            }
        }else{
            $data['user_labels'] = [];
        }

        if(mb_strlen($data['user_name'] ?? '' ) > 20){
            return $this->fail(200004, [], '用户名过长');
        }

        if(!_empty_($data['user_name'])){
            if(WxUser::where([['user_name','=',$data['user_name']], ['id', '<>', $uid] ])->exists()){
                return $this->fail(200004, [], '用户名已存在');
            }
        }

        $old_user_name = $old_user->user_name;
        $old_user_avatar = $old_user->user_avatar;
        $old_gender = $old_user->gender;
        $old_user_introduce = $old_user->user_introduce;
        $old_user_background_maps = $old_user->user_background_maps;
        $old_wechat_account = $old_user->wechat_account;

        if(_array_key($data, 'wechat_account', '')){
            if($old_wechat_account == _array_key($data, 'wechat_account', '')){
                $data['wechat_account'] = '';
            }
        }

        $user_name = $data['user_name'];
        $user_introduce = $data['user_introduce'] ?? '';

        // 百度审核
        $need_manual_review = true;
        $is_audit_user_info = Settings::get('is_audit_user_info', 0);
        if ($is_audit_user_info == 2 ) {
            if($old_user_name == $user_name && $old_user_introduce == $user_introduce){
                $need_manual_review = false;
            }else{
                if($user_name || $user_introduce){
                    $filter_result = BaiduUtils::text_filter($user_name .'  '. $user_introduce);
                    if($filter_result){
                        if($filter_result['hit_level'] == 2){
                            // 不合规
                            return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                        }else if($filter_result['hit_level'] == 0){
                            // 审核通过
                            $need_manual_review = false;
                        }
                    }
                }
            }
        }else if($is_audit_user_info == 0){
            $need_manual_review = true;
            if($old_user_name == $user_name && $old_user_introduce == $user_introduce){
                $need_manual_review = false;
            }
        }else{
            $need_manual_review = false;
        }


        if(UserUtils::is_mini_supder_admin($uid)){
            $need_manual_review = false;
        }

        $r = WxUserRepositores::update($uid, $data, $need_manual_review);
        if($r){
            UserInputSafeCheckJob::dispatch($uid, ($user_name .'  '. $user_introduce));
            Utils::image_state_change([$data['user_avatar'] ?? '', $data['user_background_maps'] ?? '' ], 1);

            if(_array_key($data, 'user_background_maps', '')){
                if($old_user_background_maps != _array_key($data, 'user_background_maps', '')){
                    UserBgColorUpdateJob::dispatch($uid, false);
                }
            }

            if($need_manual_review){
                UserUtils::assistant_notice('admin', '有用户修改资料待审核');
                return $this->success(['code'=>0]);
            }else{
                Cache::forget('get:cached:user:'.$uid);
                $login_user = WxUser::where('id', $uid)->first(FieldUtils::userInfoColums());
                // 超级管理员
                if($login_user->is_official){
                    if(UserUtils::is_mini_supder_admin($login_user->id)){
                        $login_user->is_official = 2;
                    }
                }
                UserUtils::user_expend($login_user, true, true, true, true, 5);
                $login_user->timeStamp = time();

                return $this->success(['code'=>1, 'user'=>$login_user]);
            }

        }
        return $this->fail(200002);
    }

    /**
     * 我的笔记列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMyPosts(Request $request)
    {
        $uid = $request->uid;
        $user_id = _empty_default_($request->user_id, 0);
        $limit = $request->input('limit', 10);
        $type = $request->input('type', 0);


        if($type == 'shop'){
            $orderBy = _empty_default_($request->orderBy, 'sort');
            if(!in_array($orderBy, ['id','sort', 'buys', 'created_at', 'price'])){
                return $this->fail(200004);
            }
            $order = _empty_default_($request->order, 'desc');
            if(!in_array($order, ['desc', 'asc'])){
                return $this->fail(200004);
            }
            if($orderBy != 'price'){
                $order = 'desc';
            }
        }else{
            $orderBy = 'id';
            $order = 'desc';
        }



        if(is_numeric($type)){
            $type_map = [
                0 => 'post',
                1 => 'collected',
                2 => 'liked',
                3 => 'exceptionaled',
                4 => 'voted'
            ];
            $type = $type_map[(int)$type];
        }

        if(!_empty_($user_id)){
            if($user_id > 0 || ($user_id < 0 && $type == 'post')){
                return $this->success(PostsRepositores::myPosts($user_id, $limit, $type, $orderBy, $order));
            }else{
                return $this->fail(200004);
            }
        }else{
            if($uid > 0){
                return $this->success(PostsRepositores::myPosts($uid, $limit, $type, $orderBy, $order));
            }else{
                return $this->fail(503002);
            }
        }
    }

    /**
     * 用户认证
     */
    public function authentication(Request $request)
    {
        $uid = $request->uid;
        $device = in_array($request->header('device',''), ['app', 'h5', 'mp', 'pc']) ? $request->header('device','') : '';

        $arr = UserUtils::user_action_permissions_check($uid, 'user_authenticate');
        if($arr['code'] == 0){
            return $this->fail(200000, [], $arr['msg']);
        }

        $name = $request->name;
        $contact_information = $request->contact_information;
        $introduce = $request->introduce;
        $identity_picture = $request->identity_picture;

        if(Settings::get('app_user_authenticate_img_require', 1) == 1 && _empty_($identity_picture)){
            return $this->fail(200001, [], '请上传身份信息证明图片');
        }

        $authenticationState = (new WxAuthentication())->where('user_id', $uid)->value('authentication_state');
        $authId = (new WxAuthentication())->where('user_id', $uid)->value('id');
        // 已经审核通过和驳回
        if ($authenticationState == 1 || $authenticationState == 2) {
            $model = (new WxAuthentication())->find($authId);
            $model->name = $name;
            $model->contact_information = $contact_information;
            $model->introduce = $introduce;

            $model->authentication_state = 0;
            $model->user_id = $uid;

            if(!_empty_($identity_picture)){
                $model->identity_picture = $identity_picture;
            }
            $model->save();
        }else if($authenticationState === 0){
            return $this->fail(200010, [], '您的认证信息正在审核中...请勿重复提交');
        }else if ($authenticationState === null) {
            $model = new WxAuthentication();
            $model->name = $name;
            $model->contact_information = $contact_information;
            $model->introduce = $introduce;
            if(!_empty_($identity_picture)){
                $model->identity_picture = $identity_picture;
            }
            $model->user_id = $uid;
            $model->save();
        }

        Utils::image_state_change([$identity_picture], 1);

        $tmplIds = [];
        if($device == 'mp'){
            $comment_add_id = Settings::get('mini_template_message_authentication', '');
            if(!_empty_($comment_add_id)){
                $tmplIds[] = $comment_add_id;
            }
        }

        UserUtils::assistant_notice_review(109, $model->id);

        return $this->success([
            'tmplIds' => $tmplIds
        ]);


    }

    /**
     * 我创建的圈子列表
     */
    public function myCircle(Request $request)
    {
        $uid = $request->uid;
        $data = WxCircle::where('user_id', $uid)->get();
        $data->map(function ($v) {
            $v->post_count = WxPost::where('circle_id', $v->id)->count();
            $v->user_circle_count = WxUserCircle::where('circle_id', $v->id)->count();
        });

        if(UserUtils::is_mini_supder_admin($uid)){
            $data = $data->toArray();
            $hall = [
                [
                    'id' => 0,
                    'circle_name' => '大厅',
                    'post_count' => WxPost::where('circle_id', 0)->count(),
                    'user_circle_count' => WxPost::where('circle_id', 0)->distinct('user_id')->count('user_id'),
                    'head_portrait' => Settings::get('about_logo', ''),
                    'circle_introduce' => '没有选择圈子的笔记'
                ]
            ];
            $data = array_merge($hall, $data);
        }

        return $this->success($data);
    }



    /**
     * 我的支付密码
     */
    public function paycode(Request $request){

        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }

        $uid = $request->uid;
        $type = $request->type;
        $password = $request->password;
        if($password && strlen($password) !== 6){
            return $this->fail(200004);
        }
        // 检查是否有支付密码
        if($type == 0){
            $paycode = get_user_meta($uid, 'paycode', 's');
            if($paycode){
                return $this->success(['status'=>1]);
            }else{
                return $this->success(['status'=>0]);
            }
        }else if($type == 1){
            if($password && strlen($password) === 6){
                update_user_meta($uid, 'paycode', $password, 's');
                return $this->success(['status'=>1]);
            }
            return $this->fail(200004);
        }else if($type == 2){
            if(Cache::has('paycode:checked:'.$uid)){
                if($password && strlen($password) === 6){
                    update_user_meta($uid, 'paycode', $password, 's');
                    Cache::forget('paycode:checked:'.$uid);
                    return $this->success(['status'=>1]);
                }
                return $this->fail(200004);
            }else{
                // 检测旧密码
                _limit_user('paycode:check:', $uid, 20);
                if($password !== get_user_meta($uid, 'paycode', 's')){
                    return $this->fail(200004, [], '您输入的旧密码错误');
                }else{
                    Cache::put('paycode:checked:'.$uid, true, 600);
                    return $this->success();
                }
            }
        }else if($type == 3){
            $phoneCode = $request->phoneCode;
            if(_empty_($phoneCode)){
                return $this->fail(200001, [], '验证码为空');
            }
            // 手机号验证
            $user = WxUser::find($uid);
            if(_empty_($user)){
                return $this->fail(200004, [], '用户不存在');
            }
            $phone = _get_origin_attribute('wx_user', [['id', '=', $uid]], 'phone');
            $idd = $user->country_code;
            if(_empty_($idd)){
                $idd = 86;
            }
            if(!Cache::has(md5($uid.':code:'.$idd.':'.$phone))){
                return $this->fail(200009, [], '验证码已过期，请重新发送');
            }
            if(Cache::get(md5($uid.':code:'.$idd.':'.$phone)) != $phoneCode){
                return $this->fail(200004, [], '验证码错误');
            }
            if($password && strlen($password) === 6){
                update_user_meta($uid, 'paycode', $password, 's');
                Cache::forget('paycode:checked:'.$uid);
                return $this->success(['status'=>1]);
            }
            return $this->fail(200004);
        }
    }

    public function avatar_frame_wear(Request $request){
        $uid = $request->uid;
        $avatar_frame_id = $request->id;

        if(_empty_($avatar_frame_id)){
            return $this->fail(200001);
        }
        $res = UserUtils::purchase_avatar_frame($uid, $avatar_frame_id);
        if($res['code'] == 200){
            return $this->success();
        }else{
            return $this->fail($res['code'], [], $res['msg']);
        }
    }

    /**
     *  会员页面数据
     * @param Request $request
     */
    public function membersdata(Request $request){
        $uid = $request->uid;
        $benefits = Settings::get('app_vip_benefits', []);
        $avatar_frame_ids = Settings::get('app_vip_user_avatar_frames', []);
        $avatar_frame_ = [];
        if($avatar_frame_ids){
            $avatar_frame_ = WxUserAvatarFrame::whereIn('id', $avatar_frame_ids)->get();
        }


        $vip_consume_invitees = get_user_meta($uid, 'vip_consume_invitees', 'j');
        if($vip_consume_invitees){

        }else{
            $vip_consume_invitees = [];
        }
        $invitees = WxUser::where('who', $uid)->whereNotIn('id', $vip_consume_invitees)->limit(5)->get(FieldUtils::userInfoColums());
        if($invitees){

        }else{
            $invitees = [];
        }


        $result = [
            'end_time' => UserUtils::get_user_member_time($uid),
            'invitees' => $invitees,
            'benefits_title' => Settings::get('app_vip_benefits_title', '会员尊享5大特权'),
            'benefits' => $benefits,
            'avatar_frames' => $avatar_frame_,
            'invitees_5_days' => Settings::get('app_vip_5_invitees_days', 90),
            'options' => Settings::get('app_vip_options', []),
        ];
        return $this->success($result);
    }

    public function invite_list(Request $request){
        $type = $request->type;
        $uid = $request->uid;
        if(!in_array($type, [1,2,3])){
            return $this->fail(200004);
        }

        if($type == 1 ){
            $data = WxUser::where('who', $uid)->orderBy('id', 'desc')->simplePaginate(10);
            if($data){
                $data->map(function ($v) {
                    $v->benifit = UserUtils::get_user_invite_benifit($v->id);
                });
                return $this->success($data);
            }
            return $this->success(200003);

        }else if( $type == 2 ){

            $data = WxUser::whereIn('who', function ($query) use ($uid){
                $query->select('id')->from('wx_user')->where('who', $uid);
            })->orderBy('id', 'desc')->simplePaginate(10);
            if($data){
                $data->map(function ($v) {
                    $v->benifit = UserUtils::get_user_invite_benifit($v->id);
                });
                return $this->success($data);
            }
            return $this->success(200003);
        }else if( $type == 3 ){
            $first_userIds = WxUser::where('who', $uid)->pluck('id');
            if($first_userIds){
                $first_userIds = $first_userIds->toArray();
                if($first_userIds){
                    $data = WxUser::whereIn('who', function ($query) use ($uid,$first_userIds){
                        $query->select('id')->from('wx_user')->whereIn('who', $first_userIds);
                    })->orderBy('id', 'desc')->simplePaginate(10);
                    if($data){
                        $data->map(function ($v) {
                            $v->benifit = UserUtils::get_user_invite_benifit($v->id);
                        });
                        return $this->success($data);
                    }

                }

            }
            return $this->success(200003);
        }

    }

    public function invite_info(Request $request){
        $uid = $request->uid;
        $result = [
            'notice' => Settings::get('user_invite_page_notice', ''),
            'benifit' => null,
            'myinviter' => null,
            'team' => [
                'total' => 0,
                'lv1_team' => 0,
                'lv2_team' => 0,
                'lv3_team' => 0,
            ],
            'orders' => [

            ],
            'qr' => Utils::getMiniCode('pages/tabbar/index/index', '', $uid)
        ];

        $result['benifit'] = UserUtils::get_user_invite_benifit($uid);
        $who = WxUser::where('id', $uid)->value('who');
        if($who > 0){
            $inviter = WxUser::find($who, FieldUtils::userInfoColums());
            if($inviter){
                $inviter->benifit = UserUtils::get_user_invite_benifit($inviter->id);
                $result['myinviter'] = $inviter;
            }else{
                $result['myinviter'] = null;
            }
        }


        $my_inviter_users = [];

        $first_userIds = WxUser::where('who', $uid)->pluck('id');
        $second_userIds = null;
        $third_userIds = null;
        if($first_userIds){
            $first_userIds = $first_userIds->toArray();
            $second_userIds = WxUser::whereIn('who', $first_userIds)->pluck('id');
            if($second_userIds){
                $second_userIds = $second_userIds->toArray();
                $third_userIds = WxUser::whereIn('who', $second_userIds)->pluck('id');
                if($third_userIds){
                    $third_userIds = $third_userIds->toArray();
                }
            }
        }

        if($first_userIds){
            foreach ($first_userIds as $user_id){
                if(!isset($my_inviter_users[$user_id])){
                    $my_inviter_users[$user_id] = $user_id;
                }
            }
        }
        if($second_userIds){
            foreach ($second_userIds as $user_id){
                if(!isset($my_inviter_users[$user_id])){
                    $my_inviter_users[$user_id] = $user_id;
                }
            }
        }
        if($third_userIds){
            foreach ($third_userIds as $user_id){
                if(!isset($my_inviter_users[$user_id])){
                    $my_inviter_users[$user_id] = $user_id;
                }
            }
        }

        $result['team']['total'] = $my_inviter_users ? count($my_inviter_users) : 0;
        $result['team']['lv1_team'] = $first_userIds ? count($first_userIds) : 0;
        $result['team']['lv2_team'] = $second_userIds ? count($second_userIds) : 0;
        $result['team']['lv3_team'] = $third_userIds ? count($third_userIds) : 0;


        $records_ = [];
        $records = WxUserInviteBenefitRecord::where('lv1_user', $uid)->orWhere('lv2_user', $uid)->orWhere('lv3_user', $uid)->orderBy('created_at', 'desc')->limit(5)->get();
        if($records){
            foreach ($records as $record){
                $benefit = 0;
                if($record->lv1_user == $uid){
                    $benefit = $record->lv1_benefit;
                }else if($record->lv2_user == $uid){
                    $benefit = $record->lv2_benefit;
                }else if($record->lv3_user == $uid){
                    $benefit = $record->lv3_benefit;
                }
                if($benefit < 0.01){
                    continue;
                }
                $user_name = UserUtils::get_cached_user_name($record->user_id);
                if($record->shop_order_id > 0){
                    $str = '一笔来自「<a href="/pages/user/user?id='.(int)$record->user_id.'" target="_blank">'.$user_name.'</a>」的商城订单，您获得团队奖励￥'.$benefit;
                }else if($record->order_id){
                    $str = '一笔来自「<a href="/pages/user/user?id='.(int)$record->user_id.'" target="_blank">'.$user_name.'</a>」的普通订单，您获得团队奖励￥'.$benefit;
                }

                $records_[] = $str;
            }
        }
        $result['orders'] = $records_;

        return $this->success($result);
    }

    /**
     * 激励视频奖励
     */
    public function reward_gift(Request $request){
        global $__MINI_GLOBAL_PAYCODE_14__,$__MINI_GLOBAL_DEVICE__;
        if(!$__MINI_GLOBAL_PAYCODE_14__){
            return $this->fail(700000);
        }
        $action = $request->action;
        $uid = $request->uid;
        _limit_user('reward_gift', $uid, 20);
        if($__MINI_GLOBAL_DEVICE__ == 'mp'){
            $reward_every = Settings::get('ad_mp_reward_every');
        }else{
            $reward_every = Settings::get('ad_uni_reward_every');
        }
        $count = WxUserCoinRecord::where([
            ['user_id', '=', $uid],
            ['type', '=', 10],
            ['created_at', '>=', Carbon::today()]
        ])->count();
        if($__MINI_GLOBAL_DEVICE__ == 'mp'){
            $every_day_max = Settings::get('ad_mp_reward_every_day_times', 10);
        }else{
            $every_day_max = Settings::get('ad_uni_reward_every_day_times', 10);
        }
        if($count > $every_day_max){
            return $this->fail(200010, [], '您今天获取奖励超过最大次数了，请您明天再来试试吧');
        }
        if($action == 'code'){
            if($count <= $every_day_max){
                $code = Utils::getSn(10);
                Cache::put($code, 1, 80);
                return $this->success($code);
            }else{
                return $this->fail(200010, [], '您今天获取奖励超过最大次数了，请您明天再来试试吧');
            }
        }else if($action == 'reward'){
            $code = $request->code;
            if(_empty_($code)){
                return $this->fail(200001);
            }
            if(Cache::has($code)){
                $r = UserUtils::update_user_coins($uid,10, $reward_every, '观看激励视频奖励：'.Settings::get('app_coin_name', '硬币').'(枚)*'.$reward_every);
                Cache::forget($code);
                return $this->success([], 200, '恭喜获得'.$reward_every.Settings::get('app_coin_name', '硬币'));
            }else{
                return $this->fail(200004);
            }
        }

    }

    /**
     * 我的二维码卡片
     */
    public function codecard(Request $request){

        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }

        $uid = $request->uid;
        $user_id = $request->user_id;
        if(_empty_($uid) && _empty_($user_id)){
            return $this->fail(200001);
        }

        if($user_id){
            $code = Utils::getMiniCode('pages/user/user', 'id='.$user_id, $uid);
            $user = WxUser::where('id', $user_id)->first(FieldUtils::userInfoColums());
        }else{
            $code = Utils::getMiniCode('pages/user/user', 'id='.$uid, $uid);
            $user = WxUser::where('id', $uid)->first(FieldUtils::userInfoColums());
        }
        if(_empty_($user->user_background_maps)){
            $user->user_background_maps = Settings::get('user_background_maps', '');
        }
        if(_empty_($user->user_introduce)){
            $user->user_introduce = Settings::get('app_user_introduce', '',true);
        }
        if($user){
            if(Settings::get('app_user_qrcode_way', 0) == 2){
                $result = [
                    'user_background_maps' => $user->user_background_maps . '?imageMogr2/crop/330x200/gravity/center/thumbnail/330x/rradius/20',
                    'user_avatar' => Utils::imgWithStyle($user->user_avatar, 2),
                    'user_name' => mb_strlen($user->user_name) > 8 ? (mb_substr($user->user_name, 0, 8).'...') : $user->user_name,
                    'id' => $user->id,
                    'user_introduce' => $user->user_introduce,
                    'rect' => 'https://img.mini.minisns.cn/hbx/qrcode_white_bg.png?imageMogr2/crop/330x390/gravity/center/thumbnail/330x/rradius/20',
                    'code' => $code . '?imageMogr2/format/png/interlace/0',
                    'logo' => Utils::imgWithStyle(Settings::get('about_logo', ''), 2),
                    'way' => 2
                ];
            }else{
                $result = [
                    'user_background_maps' => Utils::imgWithStyle($user->user_background_maps, 1),
                    'user_avatar' => $user->user_avatar . '?imageMogr2/crop/68x68/gravity/center/thumbnail/68x/rradius/68',
                    'user_name' => mb_strlen($user->user_name) > 8 ? (mb_substr($user->user_name, 0, 8).'...') : $user->user_name,
                    'id' => $user->id,
                    'user_introduce' => $user->user_introduce,
                    'code' => $code,
                    'logo' => Utils::imgWithStyle(Settings::get('about_logo', ''), 2),
                    'way' => 1
                ];
            }

            return $this->success($result);
        }
        return $this->fail(200003);
    }

    /**
     * 获取我的认证信息
     */
    public function getAuthentication(Request $request)
    {
        $uid = $request->uid;
        return $this->success(WxAuthentication::where('user_id', $uid)->first());
    }

    /**
     * 个人中心 我的笔记，收藏，喜欢，充电的文章数量
     * @param Request $request
     */
    public function totalPost(Request $request)
    {
        $uid = $request->uid;
        if($uid && $uid > 0){
            $query = WxPost::where('user_id', $uid)->whereIn('posts_state', [0, 2]);
            $data['myTotal'] = $query->count();
            $postsIds = WxLike::where('user_id', $uid)->pluck('posts_id');
            $data['likeTotal'] = WxPost::where('is_examine', 1)->where('posts_state', 0)->whereIn('id', $postsIds)->count();
            $postsIds = WxCollect::where('user_id', $uid)->pluck('posts_id');
            $data['collecTotal'] = WxPost::where('is_examine', 1)->where('posts_state', 0)->whereIn('id', $postsIds)->count();
            $postsIds = WxExceptional::where('user_id', $uid)->pluck('posts_id');
            $data['exceptionalTotal'] = WxPost::where('is_examine', 1)->where('posts_state', 0)->whereIn('id', $postsIds)->count();
        }else{
            $data = [
                'myTotal' => 0,
                'likeTotal' => 0,
                'collecTotal' => 0,
                'exceptionalTotal' => 0
            ];
        }

        return $this->success($data);
    }

    /**
     * 我关注的用户列表
     * @param Request $request
     */
    public function myFollowUsers(Request $request)
    {
        $uid = $request->uid;
        $user_id = $request->user_id;
        if ($user_id > 0) {
            $data = WxUserFollow::with('followUser')->where('user_id', $user_id)
                ->orderBy('id', 'desc')
                ->simplePaginate(10);
            $data->map(function ($v) use ($user_id, $uid) {
                $v->is_together_follow = WxUserFollow::where('user_id', $v->user_follow_id)
                    ->where('user_follow_id', $user_id)->exists();// 是否相互关注
                $v->user = $v->followUser;
                $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->user_follow_id);
            });
            return $this->success($data);
        } else {
            $data = WxUserFollow::with('followUser')->where('user_id', $uid)
                ->orderBy('id', 'desc')
                ->simplePaginate(10);
            $data->map(function ($v) use ($uid) {
                $v->is_together_follow = WxUserFollow::where('user_id', $v->user_follow_id)
                    ->where('user_follow_id', $uid)->exists();// 是否相互关注
                $v->user = $v->followUser;
                $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->user_follow_id);
            });
            return $this->success($data);
        }

    }


    /**
     * 我的粉丝用户列表
     * @param Request $request
     */
    public function myFansUsers(Request $request)
    {
        $uid = $request->uid;
        $user_id = $request->user_id;

        if ($user_id > 0) {
            $data = WxUserFollow::with('user')->where('user_follow_id', $user_id)
                ->orderBy('id', 'desc')
                ->simplePaginate(15);
            $data->map(function ($v) use ($user_id, $uid) {
                $v->is_together_follow = WxUserFollow::where('user_id', $user_id)
                    ->where('user_follow_id', $v->user_id)->exists();// 是否相互关注
                $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->user_id);
            });

            return $this->success($data);
        } else {
            $data = WxUserFollow::with('user')->where('user_follow_id', $uid)
                ->orderBy('id', 'desc')
                ->simplePaginate(15);
            $data->map(function ($v) use ($uid) {
                $v->is_together_follow = WxUserFollow::where('user_id', $uid)
                    ->where('user_follow_id', $v->user_id)->exists();// 是否相互关注
                $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->user_id);
            });

            return $this->success($data);
        }

    }
    /**
     * 艾特搜索
     * @param Request $request
     */
    public function aiteSearch(Request $request){
        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }
        $keyword = $request->keyword;
        $uid = $request->uid;
        _limit_user('search', $uid, 60);
        $limit = $request->input('limit', 10);

        if(_empty_($keyword)){
            $data = WxUser::whereIn('id', WxUserFollow::select('user_follow_id')->where('user_id', $uid)
                ->orderBy('id', 'desc')
            )->simplePaginate($limit);
        }else{
            $keyword_actree = null;
            $data = SearchUtils::search_user($keyword_actree, $keyword, $uid, false, $limit);
        }
        return $this->success($data);
    }
    /**
     * 获取用户列表
     * @param Request $request
     */
    public function getUsers(Request $request)
    {
        $uid = $request->uid;
        $type = $request->type;
        $limit = $request->limit;
        if(_empty_($limit)){
            $limit = 10;
        }else{
            $limit = _between_($limit, 1, 100);
        }
        $page = _empty_default_($request->page, 1);
        $object_id = _empty_default_($request->object_id, 0);

        if(_empty_($type)){
            return $this->fail(200001);
        }
        if($type == 1){
            // 最近注册用户列表
            $data = WxUser::where('user_state', 0)->orderBy('created_at', 'desc')->simplePaginate($limit, FieldUtils::userInfoColums());
            if($data){
                $data->map(function ($v) use ($uid){
                    $online_item = WxUserOnline::where('user_id', $v->id)->first(['online', 'device']);
                    if($online_item){
                        $v->online_time = format_datetime($online_item->online);
                        $v->device = $online_item->device;
                    }else{
                        $v->online_time = '暂时未知';
                        $v->device = '';
                    }
                    $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->id);
                    return $v;
                });
            }
            return $this->success($data);
        }else if($type == 2){
            // 在线用户列表
            $data = UserUtils::user_onlines(2, 5, 1);
            if($data){
                $data->map(function ($v) use ($uid){
                    $online_item = WxUserOnline::where('user_id', $v->id)->first(['online', 'device']);
                    if($online_item){
                        $v->online_time = format_datetime($online_item->online);
                        $v->device = $online_item->device;
                    }else{
                        $v->online_time = '暂时未知';
                        $v->device = '';
                    }
                    $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->id);
                    return $v;
                });
            }

            return $this->success($data);
        }else if($type == 3){
            // 今日注册的用户
            $data = WxUser::where('created_at', '>', Carbon::today())->orderBy('created_at', 'desc')->simplePaginate($limit, FieldUtils::userInfoColums());
            if($data) {
                $data->map(function ($v) use ($uid){
                    $online_item = WxUserOnline::where('user_id', $v->id)->first(['online', 'device']);
                    if ($online_item) {
                        $v->online_time = format_datetime($online_item->online);
                        $v->device = $online_item->device;
                    } else {
                        $v->online_time = '暂时未知';
                        $v->device = '';
                    }
                    $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->id);
                    return $v;
                });
            }
            return $this->success($data);
        }else if($type == 4){
            // 余额排行
            $data = DB::table('wx_user')->select(['wx_user.id', 'wx_user.user_name', 'wx_user.user_avatar', 'wx_user.user_introduce','wx_user.user_birthday', 'wx_user.user_background_maps', 'wx_user.is_authentication', 'wx_user.is_member', 'wx_user.is_official', 'wx_user.gender', 'wx_user.country_code','wx_user.phone', 'wx_user.real_name', 'wx_user.wechat_account', 'wx_user.shop_id', 'wx_user.user_state', 'wx_user.shop_id','wx_user.country', 'wx_user.province', 'wx_user.city', 'wx_user.district','wx_user.longitude', 'wx_user.latitude', 'wx_user.weixin_unionid', 'wx_user.created_at','wx_user_financial.balance'])->leftJoin('wx_user_financial', 'wx_user.id', '=', 'wx_user_financial.user_id')
                ->where('wx_user_financial.balance', '>', 0)->orderBy('wx_user_financial.balance', 'desc')->orderBy('wx_user.id')
                ->simplePaginate($limit, FieldUtils::userInfoColums());
            if($data){
                $data->map(function ($v) use ($uid){
                    $online_item = WxUserOnline::where('user_id', $v->id)->first(['online', 'device']);
                    if ($online_item) {
                        $v->online_time = format_datetime($online_item->online);
                        $v->device = $online_item->device;
                    } else {
                        $v->online_time = '暂时未知';
                        $v->device = '';
                    }
                    $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->id);
                    $v->desc_tip = '拥有'.$v->balance.'余额';
                    return $v;
                });
            }
            return $this->success($data);
        }else if($type == 5){
            // 金币排行用户
            $data = DB::table('wx_user')->select(['wx_user.id', 'wx_user.id', 'wx_user.user_name', 'wx_user.user_avatar', 'wx_user.user_introduce','wx_user.user_birthday', 'wx_user.user_background_maps', 'wx_user.is_authentication', 'wx_user.is_member', 'wx_user.is_official', 'wx_user.gender', 'wx_user.country_code','wx_user.phone', 'wx_user.real_name', 'wx_user.wechat_account', 'wx_user.shop_id', 'wx_user.user_state', 'wx_user.shop_id','wx_user.country', 'wx_user.province', 'wx_user.city', 'wx_user.district','wx_user.longitude', 'wx_user.latitude', 'wx_user.weixin_unionid', 'wx_user.created_at','wx_user_meta_num.meta_value as coins'])
                ->leftJoin('wx_user_meta_num', function ($join) {
                    $join->on('wx_user.id', '=', 'wx_user_meta_num.user_id')
                        ->where('wx_user_meta_num.meta_key', '=', 'coins');
                })->orderBy('wx_user_meta_num.meta_value', 'desc')->orderBy('wx_user.id')
                ->simplePaginate($limit, FieldUtils::userInfoColums());
            if($data){
                $data->map(function ($v) use ($uid){
                    $online_item = WxUserOnline::where('user_id', $v->id)->first(['online', 'device']);
                    if ($online_item) {
                        $v->online_time = format_datetime($online_item->online);
                        $v->device = $online_item->device;
                    } else {
                        $v->online_time = '暂时未知';
                        $v->device = '';
                    }
                    $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->id);
                    $v->desc_tip = '拥有'.$v->coins.Settings::get('app_coin_name', '硬币');
                    return $v;
                });
            }
            return $this->success($data);
        }else if($type == 6){
            // 笔记总数排行
            $subQuery = DB::table('wx_posts')
                ->select('user_id', DB::raw('COUNT(*) as post_count'))
                ->groupBy('user_id')
                ->orderByDesc('post_count')
                ->toSql();

            $data = WxUser::join(DB::raw("({$subQuery}) as sub"), 'wx_user.id', '=', 'sub.user_id')->orderBy('post_count', 'desc')->orderBy('id')
                ->simplePaginate($limit, array_merge(FieldUtils::userInfoColums(), ['post_count']));
            if($data){
                $data->map(function ($v) use ($uid){
                    $online_item = WxUserOnline::where('user_id', $v->id)->first(['online', 'device']);
                    if ($online_item) {
                        $v->online_time = format_datetime($online_item->online);
                        $v->device = $online_item->device;
                    } else {
                        $v->online_time = '暂时未知';
                        $v->device = '';
                    }
                    $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->id);
                    $v->desc_tip = '发布了'.$v->post_count.'篇笔记';
                    return $v;
                });
            }
            return $this->success($data);
        }else if($type == 7){
            // 我拉黑的用户
            return $this->fail(200003);
        }else if($type == 8){
            // 不喜欢的用户
            $user_set = get_user_meta($uid, 'feedback:notlike:user:set', 'j');
            if($user_set){
                $user_set = array_reverse($user_set);
                $data = WxUser::whereIn('id', $user_set)
                    ->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $user_set) . '"' . ")"))->orderBy('id')->simplePaginate($limit, FieldUtils::userInfoColums());
                if($data){
                    $data->map(function ($v) use ($uid){
                        $online_item = WxUserOnline::where('user_id', $v->id)->first(['online', 'device']);
                        if ($online_item) {
                            $v->online_time = format_datetime($online_item->online);
                            $v->device = $online_item->device;
                        } else {
                            $v->online_time = '暂时未知';
                            $v->device = '';
                        }
                        $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->id);
                        return $v;
                    });
                    return $this->success($data);
                }
                return $this->fail(200003);
            }else{
                return $this->fail(200003);
            }

        }else if($type == 9){
            // 激励用户排行榜
            $data = WxUserCoinRecord::query()
                ->select('wx_user.*', DB::raw('SUM(wx_user_coin_record.incre) as total_incre'), DB::raw('COUNT(wx_user_coin_record.user_id) as coin_add_count'))
                ->join('wx_user', 'wx_user.id', '=', 'wx_user_coin_record.user_id')
                ->where('wx_user_coin_record.type', 10)
                ->groupBy('wx_user_coin_record.user_id')
                ->orderByDesc('total_incre')->orderBy('wx_user.id')
                ->simplePaginate($limit, FieldUtils::userInfoColums());
            if($data){
                $data->map(function ($v) use ($uid){
                    $v->desc_tip = '支持了'.$v->coin_add_count.'次';
                    return $v;
                });
                return $this->success($data);
            }
            return $this->success($data);
        }else if($type == 10){
            // 邀请榜
            $data = WxUser::query()
                ->join('wx_user as inviters', 'inviters.id', '=', 'wx_user.who') // 连接wx_user表来获取邀请人信息
                ->select('wx_user.who as from_who', DB::raw('count(*) as total_invites'), 'inviters.id', 'inviters.user_name', 'inviters.user_avatar', 'inviters.user_introduce','inviters.user_birthday', 'inviters.user_background_maps', 'inviters.is_authentication', 'inviters.is_member', 'inviters.is_official', 'inviters.gender', 'inviters.country_code','inviters.phone', 'inviters.real_name', 'inviters.wechat_account', 'inviters.shop_id', 'inviters.user_state', 'inviters.shop_id','inviters.country', 'inviters.province', 'inviters.city', 'inviters.district','inviters.longitude', 'inviters.latitude', 'inviters.weixin_unionid', 'inviters.created_at') // 选择所需字段
                ->where('wx_user.who', '>', 0) // 确保'who'字段不为空
                ->groupBy('wx_user.who') // 按'who'字段分组，同时包括邀请人的信息
                ->orderByDesc('total_invites')->orderBy('inviters.id') // 按邀请数降序排序
                ->simplePaginate($limit);
            if($data){
                $data->map(function ($v) use ($uid){
                    $v->desc_tip = '直接邀请'.$v->total_invites.'人';
                    return $v;
                });
                return $this->success($data);
            }
            return $this->success($data);
        }else if($type == 11){
            // 粉丝排行榜
            $data = WxUser::query()
                ->join('wx_user_follow', 'wx_user.id', '=', 'wx_user_follow.user_follow_id')
                ->select('wx_user.id', 'wx_user.user_name', 'wx_user.user_avatar', 'wx_user.user_introduce','wx_user.user_birthday', 'wx_user.user_background_maps', 'wx_user.is_authentication', 'wx_user.is_member', 'wx_user.is_official', 'wx_user.gender', 'wx_user.country_code','wx_user.phone', 'wx_user.real_name', 'wx_user.wechat_account', 'wx_user.shop_id', 'wx_user.user_state', 'wx_user.shop_id','wx_user.country', 'wx_user.province', 'wx_user.city', 'wx_user.district','wx_user.longitude', 'wx_user.latitude', 'wx_user.weixin_unionid', 'wx_user.created_at', DB::raw('COUNT(wx_user_follow.user_id) as followers_count'))
                ->where('wx_user_follow.user_follow_state', 0) // 只计算正常关注的情况
                ->groupBy('wx_user.id')
                ->orderByDesc('followers_count')->orderBy('wx_user.id') // 根据粉丝数量降序排序
                ->simplePaginate($limit);
            if($data){
                $data->map(function ($v) use ($uid){
                    $v->desc_tip = '粉丝数'.$v->followers_count.'人';
                    return $v;
                });
                return $this->success($data);
            }
            return $this->success($data);
        }else if($type == 12){
            // 等级排行榜
            $data = WxUser::query()
                ->select('wx_user.id', 'wx_user.user_name', 'wx_user.user_avatar', 'wx_user.user_introduce','wx_user.user_birthday', 'wx_user.user_background_maps', 'wx_user.is_authentication', 'wx_user.is_member', 'wx_user.is_official', 'wx_user.gender', 'wx_user.country_code','wx_user.phone', 'wx_user.real_name', 'wx_user.wechat_account', 'wx_user.shop_id', 'wx_user.user_state', 'wx_user.shop_id','wx_user.country', 'wx_user.province', 'wx_user.city', 'wx_user.district','wx_user.longitude', 'wx_user.latitude', 'wx_user.weixin_unionid', 'wx_user.created_at', 'meta_num.meta_value as experience')
                ->joinSub(function ($query) {
                    $query->from('wx_user_meta_num')
                        ->select('user_id', 'meta_value')
                        ->where('meta_key', 'experience');
                }, 'meta_num', 'meta_num.user_id', 'wx_user.id')
                ->orderBy('experience', 'desc')->orderBy('wx_user.id') // 根据经验值降序排序
                ->simplePaginate($limit);

            if($data){
                $data->map(function ($v) use ($uid){
                    $v->desc_tip = '经验值'.$v->experience;
                    return $v;
                });
                return $this->success($data);
            }
            return $this->success($data);
        }else if($type == 13){
            // 俱乐部粉丝
            $data = DB::table('wx_club_follow as wcf')
                ->join('wx_user as wu', 'wcf.user_id', '=', 'wu.id')
                ->select('wu.*', 'wcf.created_at as follow_time')
                ->where('wcf.club_id', $object_id)
                ->where('wcf.status', 1) // 只获取状态为关注的记录
                ->orderBy('wcf.created_at', 'desc')
                ->simplePaginate($limit);
            if($data){
                $data->map(function ($v) use ($uid){
                    $v->desc_tip = '关注时间：'.$v->follow_time;
                    return $v;
                });
                return $this->success($data);
            }
            return $this->success($data);
        }else if($type == 14){
            // 关注圈子的粉丝
            $data = DB::table('wx_user_circle as wcf')
                ->join('wx_user as wu', 'wcf.user_id', '=', 'wu.id')
                ->select('wu.*', 'wcf.created_at as follow_time')
                ->where('wcf.circle_id', $object_id)
                ->where('wcf.user_circle_state', 0) // 只获取状态为关注的记录
                ->orderBy('wcf.created_at', 'desc')
                ->simplePaginate($limit);
            if($data){
                $data->map(function ($v) use ($uid){
                    $v->desc_tip = '关注时间：'.$v->follow_time;
                    return $v;
                });
                return $this->success($data);
            }
            return $this->success($data);
        }else if($type == 15){
            // 俱乐部-收藏过俱乐部活动的人
            $data = DB::table('wx_bureau_collect as wbc')
                ->join('wx_user as wu', 'wbc.user_id', '=', 'wu.id')
                ->select('wu.*', 'wbc.bureau_id as collect_object_id')
                ->where('wbc.club_id', $object_id)
                ->where('wbc.status', 1) // 只获取状态为收藏的记录
                ->orderBy('wbc.created_at', 'desc') // 按照收藏时间降序排序
                ->simplePaginate($limit);
            if($data){
                $data->map(function ($v) use ($uid){
                    $v->desc_tip = '收藏的「组局id: '.$v->collect_object_id.'」';
                    return $v;
                });
                return $this->success($data);
            }
            return $this->success($data);
        }else if($type == 16){
            // todo: 这个有问题
            $data = WxUser::select('wx_user.*', 'wx_bureau.id as join_bureau_id')
                ->join('wx_shop_order_goods', 'wx_user.id', '=', 'wx_shop_order_goods.seller_user_id')
                ->join('wx_bureau', 'wx_shop_order_goods.goods_id', '=', 'wx_bureau.id')
                ->where('wx_bureau.club_id', $object_id)
                ->where('wx_shop_order_goods.goods_type', 7)
                ->where('wx_shop_order_goods.state', '<>', 3)
                ->orderBy('wx_shop_order_goods.created_at', 'desc')
                ->distinct()
                ->simplePaginate($limit);
            if($data){
                $data->map(function ($v) use ($uid){
                    $v->desc_tip = '参加的「组局id: '.$v->join_bureau_id.'」';
                    return $v;
                });
                return $this->success($data);
            }
            return $this->success($data);
        }else if($type == 17){
            // 获取传单所推广的用户
            $itcId = (int)str_replace('itc', '', _empty_default_($request->itc, ''));
            if(_empty_($itcId)){
                return $this->fail(200001);
            }
            $data = DB::table('wx_user as u')
                ->join('wx_user_invite_temp_code_record as r', 'u.id', '=', 'r.object_id')
                ->where('r.itc_id', $itcId)
                ->orderBy('r.created_at', 'desc')
                ->select('u.*', 'r.created_at', 'r.*')->simplePaginate($limit);
            $data->map(function ($v) use ($uid){
                $v->desc_tip = $v->created_at . '  奖励:￥' . $v->reward_balance . ($v->reward_coin > 0 ? '+'.Settings::get('app_coin_name', '硬币').'*'.$v->reward_coin : '');
                return $v;
            });
            return $this->success($data);
        }
    }
    /**
     * 添加用户话题
     * @param Request $request
     */
    public function addUserPlate(Request $request)
    {
        $plateId = $request->plate_id;
        $uid = $request->uid;
        if(_empty_($plateId)){
            return $this->fail(200001);
        }
        $r = UserUtils::add_user_plate($uid, $plateId);
        if($r){
            return $this->success();
        }
        return $this->fail(200004, [], '添加分区失败');
    }

    public function real_name(Request $request)
    {
        $uid = $request->uid;
        if(request()->method() === 'GET'){
            $user = WxUser::where('id', $uid)->first(['id', 'real_name', 'real_id_card']);
            if($user){
                if(_empty_($user->real_name)){
                    $user->real_name = '';
                }
                if(_empty_($user->real_id_card)){
                    $user->real_id_card = '';
                }
                return $this->success($user);
            }else{
                return $this->fail(200003);
            }
        }else{
            $user = WxUser::find($uid);
            if(_empty_($user)){
                return $this->fail(200003);
            }

            $realName = _empty_default_($request->realName, '');
            $realIdCard = _empty_default_($request->realIdCard, '');

            if(_empty_($realName) || _empty_($realIdCard)){
                return $this->fail(200001);
            }

            if(mb_strlen($realName) <= 1){
                return $this->fail(200004, [], '姓名过短');
            }

            if(strpos($realName, '*') !== false || strpos($realIdCard, '*') !== false){
                return $this->fail(200004, [], '姓名或身份证中含有*号，请先删除');
            }

            if(strlen($realIdCard) != 18){
                return $this->fail(200004, [], '请输入合法的身份证号');
            }

            $realName_fake = mb_substr($realName, 0, 1) . str_repeat( '*',  (mb_strlen($realName) - 1) );
            $realIdCard_fake = mb_substr($realIdCard, 0, 2) . str_repeat( '*', (mb_strlen($realIdCard) - 2) );

            if($user->real_name == $realName_fake && $user->real_id_card == $realIdCard_fake){
                return $this->fail(200010, [], '与已有认证信息相同，无需修改');
            }

            $phone = _get_origin_attribute('wx_user', [['id', '=', $uid]], 'phone');
            if(_empty_($user->phone) || _empty_($phone)){
                return $this->fail(200043, [
                    'title' => '未绑定手机号',
                    'content' => '前往绑定',
                    'confirmText' => '去绑定',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/editmine/editmine?phone=1'
                ], '未绑定手机号');
            }
            $res_ = Http::withHeaders([
                'Authorization' => 'APPCODE '.Settings::get('app_ali_real_name_appcode', ''),
            ])->asForm()->post('https://mobile3elements.shumaidata.com/mobile/verify_real_name', ['idcard'=>$realIdCard, 'mobile'=>$phone, 'name'=> $realName]);
            if($res_->successful()){
                $res = $res_->json();
                if($res){
                    if($res['code'] == 0 && $res['result']){
                        if($res['result']['res'] == 1){
                            // 一致
                            DB::beginTransaction();
                            try {
                                $encrypted = SafeUtils::mini_common_rsa_encrypt('id='.$realIdCard.':name='.$realName.':phone=('.$user->country_code.')'.$phone);
                                // todo:
                                WxUser::where('id', $uid)->update([
                                    'real_name' => $realName_fake,
                                    'real_id_card' => $realIdCard_fake
                                ]);
                                update_user_meta($uid, 'real_info_encrypted', base64_encode($encrypted), 's');

                                DB::commit();
                                return $this->success([], 200, '实名认证成功');
                            } catch (\Exception $e) {
                                DB::rollBack();
                                _logger_(__file__, __line__, $e->getMessage());
                                return $this->fail(200002);
                            }

                        }else if($res['result']['res'] == 2){
                            return $this->fail(200004, [], '身份信息不一致，认证失败');
                        }else if($res['result']['res'] == 3){
                            return $this->fail(200004, [], '认证系统查询不到该信息，请联系客服');
                        }else if($res['result']['res'] == -1){
                            return $this->fail(200004, [], '异常');
                        }
                    }else{
                        UserUtils::assistant_notice('admin', $res.'_003');
                        return $this->fail(200004, [], $res['message'].'__003');
                    }
                }
            }else{
                $res = $res_->json();
                _logger_(__file__, __line__, '实名认证返回错误，'.$res_->body());
                _logger_(__file__, __line__, '实名认证返回错误，'. urldecode($res_));
                return $this->fail(200004, [], _array_key($res, 'message', ''));
            }


        }
    }

    /**
     * 删除用户话题
     * @param Request $request
     */
    public function deleteUserPlate(Request $request)
    {
        $id = $request->id;
        $uid = $request->uid;
        $plate_id = $request->plate_id;
        if(_empty_($plate_id)){
            (new WxUserPlate())->where('user_id', $uid)->where('id', $id)->update(['status'=>2]);
        }else{
            (new WxUserPlate())->where('user_id', $uid)->where('plate_id', $plate_id)->update(['status'=>2]);
        }
        return $this->success();
    }

    /**
     * 用户话题列表
     * @param Request $request
     */
    public function userPlate(Request $request)
    {
        global $__MINI_GLOBAL_TENANT_ID__;
        $uid = $request->uid;
        if ($uid == 0) {
            $data = [];
        } else {
            $data = (new WxUserPlate())->where('user_id', $uid)->where('status', 1)->orderBy('updated_at', 'asc')->get();
            if(!$data->isEmpty()){
                $data = $data->map(function ($item) {
                    $plate = WxPlate::find($item->plate_id);
                    if($plate){
                        $item->plate_name = $plate->plate_name;
                        $item->tenant_id = $plate->tenant_id;
                        return $item;
                    }
                });

                $data = $data->filter(function ($item, $key) use ($__MINI_GLOBAL_TENANT_ID__){
                    if($item){
                        return $item->tenant_id == $__MINI_GLOBAL_TENANT_ID__;
                    }
                    return false;
                });

            }
        }

        return $this->success($data);
    }

    /**
     * 我的订单列表
     */
    public function myOrder(Request $request, $limit = 8)
    {
        $uid = $request->uid;
        $type = $request->type;
        if(_empty_($type)){
            return $this->fail(200001);
        }
        if($type == 'all'){
            if(!UserUtils::is_mini_supder_admin($uid)){
                return $this->fail(200000);
            }
            $data = WxOrder::where([['order_state','=', 1], ['order_serial_number', '<>', '']])
                ->orderBy('id', 'desc')->simplePaginate($limit);
        }else{
            $data = WxOrder::where('user_id', $uid)->where([['order_state','=', 1], ['order_serial_number', '<>', '']])
                ->orderBy('id', 'desc')->simplePaginate($limit);
        }

        $data->map(function ($v) {
            $v->type_content = WxUserRepositores::orderType($v->order_type);
            $parame = unserialize($v->parame);
            $v->posts_id = $parame['postsId'] ?? 0;
            $v->user = WxUser::where('id', $v->user_id)->first(FieldUtils::userInfoColums());
        });

        return $this->success($data);
    }

    public function financial_process(Request $request){
        $type = _empty_default_($request->type, '');
        if ($type == 'my_financial') {
            return $this->myFinancial($request);
        }else if ($type == 'initiate_withdrawal') {
            return $this->initiateWithdrawal($request);
        }else if ($type == 'withdrawal_apply') {
            return $this->withdrawalApply($request);
        }else if ($type == 'withdrawal_list') {
            return $this->withdrawalList($request);
        }else if ($type == 'balance_record_list') {
            return $this->balanceRecordList($request);
        }else if ($type == 'coin_record_list') {
            return $this->coinRecordList($request);
        }
    }

    private function coinRecordList(Request &$request){
        $uid = $request->uid;
        $setUserid = $request->setUserid;
        if(!_empty_($setUserid)) {
            if ($setUserid && $setUserid > 0) {
                if (UserUtils::is_mini_supder_admin($uid)) {
                    $uid = $setUserid;
                } else {
                    return $this->fail(200000, [], '你不是超级管理员，无法查看');
                }
            }
        }

        $data = WxUserCoinRecord::where('user_id', $uid)->orderBy('id', 'desc')->simplePaginate(10);
        if($data){
            $data->map(function ($v) {


            });
            return $this->success($data);
        }
        return $this->fail(200003);
    }

    private function balanceRecordList(Request &$request){
        $uid = $request->uid;
        $setUserid = $request->setUserid;
        if(!_empty_($setUserid)) {
            if ($setUserid && $setUserid > 0) {
                if (UserUtils::is_mini_supder_admin($uid)) {
                    $uid = $setUserid;
                } else {
                    return $this->fail(200000, [], '你不是超级管理员，无法查看');
                }
            }
        }

        $data = WxUserFinancialRecord::where('user_id', $uid)->orderBy('id', 'desc')->simplePaginate(10);
        if($data){
            $data->map(function ($v) {


            });
            return $this->success($data);
        }
        return $this->fail(200003);
    }

    private function withdrawalList(Request &$request){
        $uid = $request->uid;
        $setUserid = $request->setUserid;
        if(!_empty_($setUserid)) {
            if ($setUserid && $setUserid > 0) {
                if (UserUtils::is_mini_supder_admin($uid)) {
                    $uid = $setUserid;
                } else {
                    return $this->fail(200000, [], '你不是超级管理员，无法查看');
                }
            }
        }

        $data = WxUserWithdrawal::where('user_id', $uid)->orderBy('id', 'desc')->simplePaginate(10);
        if($data){
            $data->map(function ($v) {
                $v->state_tip = WxUserRepositores::withdrawalType($v->state);
                if(!_empty_($v->withdrawal_remark)){
                    $v->title = $v->withdrawal_remark;
                }else if(!_empty_($v->wechat_phone)){
                    $v->way = 'wechat';
                    $v->title = '提现'.$v->pay_amount.'元到微信';
                }else if(!_empty_($v->alipay_phone)){
                    $v->way = 'alipay';
                    $v->title = '提现'.$v->pay_amount.'元到支付宝';
                }else if(!_empty_($v->bank_card)){
                    $v->way = 'bank';
                    $v->title = '提现'.$v->pay_amount.'元到银行卡';
                }

                if(_empty_($v->way)){
                    if(!_empty_($v->wx_batch_id)){
                        $v->way = 'wechat';
                    }else if(!_empty_($v->ali_batch_id)){
                        $v->way = 'alipay';
                    }
                }

            });
            return $this->success($data);
        }
        return $this->fail(200003);
    }

    private function withdrawalApply(Request &$request){
        $uid = $request->uid;
        $id = _empty_default_($request->id, 0);
        if(_empty_($id)){
            return $this->fail(200001);
        }
        $withdrawal = WxUserWithdrawal::find($id);
        if($withdrawal->user_id != $uid && !UserUtils::is_mini_supder_admin($uid)){
            return $this->fail(200000);
        }
        $withdrawal->state_tip = WxUserRepositores::withdrawalType($withdrawal->state);
        if(!_empty_($withdrawal->wechat_phone)){
            $withdrawal->way = 'wechat';
        }else if(!_empty_($withdrawal->alipay_phone)){
            $withdrawal->way = 'alipay';
        }else if(!_empty_($withdrawal->bank_card)){
            $withdrawal->way = 'bank';
        }else if(!_empty_($withdrawal->wx_batch_id)){
            $withdrawal->way = 'wechat';
        }else if(!_empty_($withdrawal->ali_batch_id)){
            $withdrawal->way = 'alipay';
        }

        return $this->success($withdrawal);
    }


    /**
     * 我的收益
     */
    public function myFinancial(Request $request)
    {
        $uid = $request->uid;
        $setUserid = $request->setUserid;
        if(!_empty_($setUserid)){
            if($setUserid && $setUserid > 0){
                if(UserUtils::is_mini_supder_admin($uid)){
                    $uid = $setUserid;
                }else{
                    return $this->fail(200000, [], '你不是超级管理员，无法查看');
                }
            }
        }
        $result = [
            'coins' => [
                'total' => UserUtils::user_coins($uid) ?? 0
            ],
            'financial' => [],
        ];
        $result['financial'] = WxUserFinancial::where('user_id', $uid)
            ->first();

        if($result['financial']) {
            $result['financial']->earnings_yesterday = WxExceptional::where('posts_user_id', $result['financial']->user_id)
                ->where('created_at', 'like', '%' . date("Y-m-d", strtotime("-1 day")) . '%')
                ->sum('exceptional_price');
            if(_empty_($result['financial']->withdrawal_price)){
                $result['financial']->withdrawal_price = 0;
            }
            return $this->success($result);
        }else{
            return $this->success($result);
        }
    }

    /**
     * 发起提现
     */
    public function initiateWithdrawal(Request $request)
    {
        global $__MINI_GLOBAL_CURRENT_PLAYER_ID__;
        $uid = $request->uid;

        $price = $request->price;
        $bank_name = _empty_default_($request->bank_name, '');
        $bank_card = _empty_default_($request->bank_card, '');

        $real_name = $request->real_name ?? null;
        $id_card = _empty_default_($request->id_card, '');
        $wechat_phone = $request->wechat_phone ?? null;
        $aliay_phone = $request->aliay_phone ?? null;
        $withdrawal_way = _empty_default_($request->way, 'wechat');

        $device = in_array($request->header('device',''), ['app', 'h5', 'mp', 'pc']) ? $request->header('device','') : '';
        if($price < Settings::get('app_balance_withdrawal_min_once', 1) || $price > Settings::get('app_balance_withdrawal_max_once', 200)){
            return $this->fail(200004, [], '提现金额不合法');
        }

        $user = WxUser::find($uid);
        // 验证资料
        if(Settings::get('app_balance_withdrawal_force_bind_phone', 0) == 1){
            if(_empty_($user->phone) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                return $this->fail(200043, [
                    'title' => '未绑定手机号',
                    'content' => '前往绑定',
                    'confirmText' => '去绑定',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/editmine/editmine?phone=1'
                ], '未绑定手机号');
            }
        }

        if(Settings::get('app_balance_withdrawal_force_real_name', 0) == 1){
            if(_empty_($user->real_name) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                return $this->fail(200043, [
                    'title' => '未实名认证',
                    'content' => '您还没有实名认证，是否前往认证',
                    'confirmText' => '去认证',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/realname/realname'
                ], '未实名认证');
            }
        }

        if(Settings::get('app_balance_withdrawal_force_subscribe_mp', 0) == 1){
            if(_empty_($user->weixin_mp_openid) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                $weapp = new WeApp('mp');
                $mpServicer = $weapp->getMpServicer();
                try {
                    $url = $mpServicer->getQrCodeWithPara(0, 'user:bind:'.$user->id);
                }catch (\Exception $e){
                    return $this->fail(200006, [], '生成公众号二维码失败，请检查[全局配置-支付-微信-公众号]');
                }
                if($url){
                    $qrCode = QrCode::format('png')->size(300)->generate($url);
                    $image = Image::make($qrCode);
                    $image->resizeCanvas(300, 300 + 60, 'bottom', false, '#ffffff'); // 增加高度，保持宽高比，背景色为白色
                    $mp_app_name = Settings::get('mp_app_name', '');
                    $text_tip = '关注'.$mp_app_name.'公众号，可以更方便通知到您';
                    if(mb_strlen($mp_app_name) > 4){
                        $text_tip = '关注'.$mp_app_name.'公众号';
                    }
                    $image->text($text_tip, 150, 40, function($font){
                        $font->file(public_path('storage/font/DingTalk_JinBuTi_Regular.ttf')); // 字体文件路径
                        $font->size(13); // 字体大小
                        $font->color('#000000'); // 字体颜色
                        $font->align('center'); // 水平对齐
                        $font->valign('top'); // 垂直对齐
                    });
                    $base64 = 'data:image/png;base64,' . base64_encode($image->encode('png')->getEncoded());
                    return $this->fail(200043, [
                        'title' => '未关注公众号，无法实时获取通知',
                        'content' => '前往关注',
                        'confirmText' => '去关注',
                        'target_type' => 26,
                        'target_id' => $base64
                    ], '未关注公众号');
                }
            }
        }

        if(_empty_($real_name)){
            return $this->fail(200001, [], '缺少真实姓名');
        }

        $financial_updates = [];
        if($withdrawal_way == 'wechat'){
            if(_empty_($wechat_phone) || !StrUtils::is_phone_number($wechat_phone)){
                return $this->fail(200001, [], '微信手机号不合法');
            }
            if(_empty_($real_name)){
                return $this->fail(200001, [], '姓名不完整');
            }
            $financial_updates['wechat_phone'] = $wechat_phone;
            $financial_updates['real_name'] = $real_name;
        }else if($withdrawal_way == 'alipay'){
            if(_empty_($aliay_phone) || !StrUtils::is_phone_number($aliay_phone)){
                return $this->fail(200001, [], '支付宝手机号不合法');
            }
            if(_empty_($real_name) || _empty_($id_card) || strlen($id_card) != 18){
                return $this->fail(200001, [], '姓名或身份证号不完整');
            }
            $financial_updates['alipay_phone'] = $aliay_phone;
            $financial_updates['real_name'] = $real_name;
            $financial_updates['id_card'] = $id_card;
        }else{
            if(_empty_($bank_name) || _empty_($bank_card) || _empty_($real_name)){
                return $this->fail(200001, [], '银行信息不完整');
            }
            $financial_updates['bank_name'] = $bank_name;
            $financial_updates['bank_card'] = $bank_card;
            $financial_updates['real_name'] = $real_name;
        }

        if(WxUserWithdrawal::where('user_id', $uid)->where('withdrawal_scene', 0)->whereDate('created_at', Carbon::today())->count() >= Settings::get('app_balance_withdrawal_day_times', 3)){
            return $this->fail(200046, [], '您今天已经达到最大的提现次数了');
        }


        $platform_percent = _between_(Settings::get('app_withdrawal_platform_percent', 10.0), 0, 100);
        $pay_amount = round(($price * ( 100 - $platform_percent )) / 100, 2);

        DB::beginTransaction();
        try{
            $r = UserUtils::update_user_financial($uid, 2, $price, '发起余额提现￥'.$price, 0, $bank_name, $bank_card);
            if($r){
                $withdrawal_id = Utils::getSn(14);
                // 提现记录
                $userWithdrawalModel = new WxUserWithdrawal();
                $userWithdrawalModel->user_id = $uid;
                $userWithdrawalModel->withdrawal_id = $withdrawal_id;
                $userWithdrawalModel->price = $price;
                $userWithdrawalModel->pay_amount = $pay_amount;
                $userWithdrawalModel->bank_name = $bank_name;
                $userWithdrawalModel->bank_card = $bank_card;

                $userWithdrawalModel->real_name = $real_name;
                if($withdrawal_way == 'wechat'){
                    $userWithdrawalModel->wechat_phone = $wechat_phone;
                    $userWithdrawalModel->alipay_phone = null;
                }else if($withdrawal_way == 'alipay'){
                    $userWithdrawalModel->wechat_phone = null;
                    $userWithdrawalModel->alipay_phone = $aliay_phone;
                }
                $userWithdrawalModel->state = 0;
                $userWithdrawalModel->save();
                UserUtils::assistant_notice('admin', '有用户（<a href="/pages/user/user?id='.$uid.'">id: '.$uid.'</a>）提交了新的提现申请。');
                WxUserFinancial::where('user_id', $uid)->update($financial_updates);
                UserWithdrawalProcessJob::dispatch($userWithdrawalModel->id);

                $tmplIds = [];
                if($device == 'mp'){
                    $comment_add_id = Settings::get('mini_template_message_withdrawal', '');
                    if(!_empty_($comment_add_id)){
                        $tmplIds[] = $comment_add_id;
                    }
                }

                DB::commit();
                return $this->success([
                    'tmplIds' => $tmplIds,
                    'id' => $userWithdrawalModel->id
                ]);
            }
            DB::rollBack();
            return $this->fail(200013);
        }catch (\Exception $e){
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200013);
        }

    }

    /**
     * 我的提现记录
     */
    public function myUserWithdrawal(Request $request)
    {
        $uid = $request->uid;
        $id = _empty_default_($request->id, 0);
        $setUserid = $request->setUserid;
        if(!_empty_($setUserid)) {
            if ($setUserid && $setUserid > 0) {
                if (UserUtils::is_mini_supder_admin($uid)) {
                    $uid = $setUserid;
                } else {
                    return $this->fail(200000, [], '你不是超级管理员，无法查看');
                }
            }
        }

        $query = WxUserWithdrawal::where('user_id', $uid);
        if($id > 0){
            $query = $query->where('id', $id);
        }
        $data = $query
            ->orderBy('id', 'desc')
            ->get();

        $data->map(function ($v) {
            $v->status_value = WxUserRepositores::withdrawalType($v->state);
        });

        return $this->success($data);
    }

    /**
     * @param Request $request
     */
    public function uploaded_unused_attachments(Request $request){
        $uid = $request->uid;
        $type = $request->type;

        if($type == 'img'){
            $types_ = ["jpg", "jpeg", "png", "gif"];
        }else if($type == 'video'){
            $types_ = ['mp4'];
        }else{
            return $this->fail(200004);
        }
        $attachments = WxAttachment::where('user_id', $uid)->where('state', 1)->WhereIn('type', $types_)->orderBy('id', 'desc')->simplePaginate(10);
        if($attachments){
            $attachments->map(function ($v){
                $v->url = $v->domain .'/' . $v->path;
                return $v;
            });
            return $this->success($attachments);
        }
        return $this->fail(200003);
    }

    /**
     * 邀请领会员
     */
    public function invite_member(Request $request)
    {
        global $__MINI_GLOBAL_PAYCODE_16__;
        if(!$__MINI_GLOBAL_PAYCODE_16__){
            return $this->fail(700000);
        }

        $uid = $request->uid;
        $days = Settings::get('app_vip_5_invitees_days', 90);
        if(_empty_($days)){
            return $this->fail(200008);
        }
        $vip_consume_invitees = get_user_meta($uid, 'vip_consume_invitees', 'j');

        $invitees = WxUser::where('who', $uid)->whereNotIn('id', $vip_consume_invitees)->limit(5)->get(FieldUtils::userInfoColums());
        if($invitees){

        }else{
            $invitees = [];
        }

        if(_empty_($invitees) || count($invitees) < 5){
            return $this->fail(200042, [], '你的邀请人数只有'.count($invitees).'个，凑够5个才能兑换会员，再接再厉');
        }

        // 满足条件
        DB::beginTransaction();
        try{
            foreach ($invitees as $invitee){
                $vip_consume_invitees[] = $invitee->id;
            }
            update_user_meta($uid, 'vip_consume_invitees', $vip_consume_invitees, 'j');
            WxUserRepositores::vip($uid, $days);
            DB::commit();
            return $this->success(['days'=>$days]);

        }catch (\Exception $e){
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200006);
        }

    }

    /**
     * 我的收益记录
     */
    public function myUserExceptional(Request $request)
    {
        $uid = $request->uid;

        $setUserid = $request->setUserid;
        if(!_empty_($setUserid)) {
            if ($setUserid && $setUserid > 0) {
                if (UserUtils::is_mini_supder_admin($uid)) {
                    $uid = $setUserid;
                } else {
                    return $this->fail(200000, [], '你不是超级管理员，无法查看');
                }
            }
        }

        $data = WxExceptional::where('posts_user_id', $uid)
            ->orderBy('id', 'desc')
            ->get();

        $data->map(function ($v) {
            $v->user = WxUser::where('id', $v->user_id)->first(FieldUtils::userInfoColums());
            $v->datetime = format_datetime($v->created_at);
        });

        return $this->success($data);
    }

    public function myVisit(Request $request){
        $uid = $request->uid;
        $page = 1; // 从请求获取或设定默认值
        $perPage = 15; // 每页显示的数量

        $visits = WxUserVisit::where('type', 1)->where('user_id', $uid)
            ->join('wx_posts', 'wx_user_visit.object_id', '=', 'wx_posts.id')
            ->select('wx_user_visit.object_id',
                DB::raw('DATE(wx_user_visit.created_at) as visit_date'),
                DB::raw('SUM(wx_user_visit.times) as total_times'),
            )
            ->groupBy('visit_date', 'wx_user_visit.object_id')
            ->orderBy('visit_date', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        return $this->success($visits);
    }

    /**
     * 我的余额记录
     */
    public function myUserFinancialRecord(Request $request)
    {
        $uid = $request->uid;

        $setUserid = $request->setUserid;
        if(!_empty_($setUserid)) {
            if ($setUserid && $setUserid > 0) {
                if (UserUtils::is_mini_supder_admin($uid)) {
                    $uid = $setUserid;
                } else {
                    return $this->fail(200000, [], '你不是超级管理员，无法查看');
                }
            }
        }

        $data = WxUserFinancialRecord::where('user_id', $uid)
            ->orderBy('id', 'desc')->limit(20)
            ->get();
        $data->map(function ($record){
            $record->type_name = FieldUtils::getUserFinancialType()[(int)$record->type];
            $record->date = $record->created_at->toDateTimeString();
            $record->num_str = $record->num > 0 ? '+'.$record->num : $record->num;
            return $record;
        });

        return $this->success($data);
    }

    /**
     * 我的金币记录
     */
    public function myUserCoinsRecord(Request $request)
    {
        $uid = $request->uid;

        $setUserid = $request->setUserid;
        if(!_empty_($setUserid)) {
            if ($setUserid && $setUserid > 0) {
                if (UserUtils::is_mini_supder_admin($uid)) {
                    $uid = $setUserid;
                } else {
                    return $this->fail(200000, [], '你不是超级管理员，无法查看');
                }
            }
        }

        $data = WxUserCoinRecord::where('user_id', $uid)
            ->orderBy('id', 'desc')->limit(20)
            ->get();

        $data->map(function ($record){
            $record->date = $record->created_at->toDateTimeString();
            $record->num_str = $record->incre > 0 ? '+'.$record->incre : $record->incre;
            return $record;
        });

        return $this->success($data);
    }

    /*
     * 用户海报数据
     */
    public function poster(Request $request){
        $userId = $request->id;
        $uid = $request->uid;
        if(_empty_($userId)){
            return $this->fail(200001);
        }

        $user = WxUser::find($userId);
        if(_empty_($user)){
            return $this->fail(200003);
        }
        global $__MINI_GLOBAL_TENANT_ID__;
        $mini_code = Utils::getMiniCode('/pages/user/user', 'id='.$user->id, $uid, 430, false, null, true);
        if($mini_code){
            $data = [
                'userdata' => [
                    'avatar' => $user->user_avatar,
                    'name' => $user->user_name
                ],
                'swiperList' => Settings::get('app_share_poster', [], true),
                'code' => $mini_code,
                'web' => rtrim(Settings::get('app_h5_home', ''), '/') . '/#/pages/user/user?id=' . $userId . '&fph=1&from_user=' . $uid .'&tenant=' . $__MINI_GLOBAL_TENANT_ID__
            ];
            if(_empty_($data['swiperList'])){
                return $this->fail(200008);
            }
            return $this->success($data);
        }else{
            return $this->fail(300001);
        }
    }

    public function earningsRank(Request $request){
        $userId = $request->uid;
        $user = WxUser::find($userId);
        if(_empty_($user)){
            return $this->fail(200003);
        }

        $r = WxUserFinancial::leftJoin('wx_user', 'wx_user.id', '=', 'wx_user_financial.user_id')->orderBy('sum_price', 'desc')->limit(10)->get(['wx_user.user_avatar', 'wx_user.user_name', 'wx_user.id', 'wx_user_financial.sum_price','wx_user_financial.withdrawal_price', 'wx_user.is_member', 'wx_user.is_official', 'wx_user.is_authentication', 'wx_user.gender']);
        if(_empty_($r)){
            return $this->fail(200003);
        }
        $data = [
            'one' => [],
            'two' => [],
            'three' => [],
            'others' => [

            ],
            'avg' => round(WxUserFinancial::avg('sum_price'), 2),
            'bg' => Settings::get('app_earnings_rank_bg', 'https://img.mini.minisns.cn/images/rank/rank_bg.png'),
            'total' => WxUserFinancial::count()
        ];
        $defaut = [
            'id' => 0,
            'user_avatar' => Settings::get('img_default_avatar', 'https://img.mini.minisns.cn/images/avatar.png'),
            'user_name' => '未知',
            'sum_price' => 0,
            'withdrawal_price' => 0,
            'is_member' => 0,
            'is_official' => 0,
            'is_authentication' => 0,
            'gender' => 0
        ];

        for ($i = 0; $i < 10; $i ++){
            if ($i == 0){
                if(isset($r[$i])){
                    $data['one'] = $r[$i];
                }else{
                    $data['one'] = $defaut;
                }
            }else if($i == 1){
                if(isset($r[$i])){
                    $data['two'] = $r[$i];
                }else{
                    $data['two'] = $defaut;
                }
            }else if($i == 2){
                if(isset($r[$i])){
                    $data['three'] = $r[$i];
                }else{
                    $data['three'] = $defaut;
                }
            }else{
                if(isset($r[$i])){
                    $data['others'][] = $r[$i];
                }else{
                    $data['others'][] = $defaut;
                }
            }
        }
        return $this->success($data);
    }

    public function vote(Request $request){
        $position = $request->position;
        $uid = $request->uid;
        $vote_id = $request->vote_id;

        if(_empty_($vote_id) || _empty_($position) || !is_numeric($position)){
            return $this->fail(200001);
        }

        if($position > 20 || $position < 1){
            return $this->fail(200004);
        }

        if(WxUserVote::where([
            ['user_id', '=', $uid],
            ['vote_id', '=', $vote_id]
        ])->exists()){
            return $this->fail(200010, [], '你已经为这个内容投过票啦');
        }

        $WxUserVote = new WxUserVote();
        $WxUserVote->user_id = $uid;
        $WxUserVote->vote_id = $vote_id;
        $WxUserVote->vote_option = $position;
        $r = $WxUserVote->save();
        if($r){
            WxPostsVote::where('id', $vote_id)->increment('num'.$position);
            return $this->success(PostUtils::getVoteData($vote_id, $uid));
        }
        return $this->fail(200002);
    }

    /**
     * 拉黑或取消拉黑某个用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function black(Request $request){
        $uid = $request->uid;
        $object_id = $request->object_id;
        $action = $request->action;

        if(_empty_($object_id)){
            return $this->fail(200001);
        }
        if($action == 'black'){
            $user_set = get_user_meta($uid, 'user:blacked:set', 'j');
            if(!in_array($object_id, $user_set)){
                $user_set[] = $object_id;
                update_user_meta($uid, 'user:blacked:set', array_unique($user_set), 'j');
                return $this->success([], 200, '拉黑成功');
            }else{
                // 要删除的特定值
                $user_set = array_filter($user_set, function ($value) use ($object_id) {
                    return $value != $object_id;
                });
                update_user_meta($uid, 'user:blacked:set', array_unique($user_set), 'j');
                return $this->success([], 200, '取消拉黑');
            }
        }else{
            $user_set = get_user_meta($uid, 'feedback:notlike:user:set', 'j');
            if(!in_array($object_id, $user_set)){
                $user_set[] = $object_id;
                update_user_meta($uid, 'feedback:notlike:user:set', array_unique($user_set), 'j');
                return $this->success();
            }else{
                // 要删除的特定值
                $user_set = array_filter($user_set, function ($value) use ($object_id) {
                    return $value != $object_id;
                });
                update_user_meta($uid, 'feedback:notlike:user:set', array_unique($user_set), 'j');
                return $this->success();
            }
        }
    }

    /**
     * 用户反馈
     * [0=>'post', 1=> 'comment', 2 => 'user', 3=> 'goods']
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function report(Request $request)
    {
        $uid = $request->uid;

        _limit_user('add:report', $uid, 20);

        $report_type = $request->report_type;
        $report_content = $request->report_content;
        $image_urls = $request->image_urls;
        $type = $request->type;
        $object_id = $request->object_id;

        if(!isset($type) || !isset($object_id)){
            return $this->fail(200001);
        }

        if(!in_array($type, [0,1,2,3,4,5,6])){
            return $this->fail(200004);
        }

        $count = WxUserReport::where([
            ['type', '=', $type],
            ['object_id', '=', $object_id],
            ['user_id', '=', $uid]
        ])->count();

        if($count > 0){
            return $this->fail(200010, [], '你已经举报过了ta，再管理员反馈之前，请勿重复举报');
        }


        $image_urls__ = [];
        if($image_urls){
            foreach ($image_urls as $img_item){
                $image_urls__[] = $img_item['url'];
            }
        }

        $contact = $request->contact;

        if(_empty_($report_content)){
            $this->fail(200001);
        }

        $r = WxUserReportRepositories::add($uid,$type, $object_id,  $report_type, $report_content, $image_urls__, $contact);
        if($r){

            $count_ = WxUserReport::where([
                ['type', '=', $type],
                ['object_id', '=', $object_id],
            ])->count();
            if($type == 0){
                $app_report_safe_times_post = Settings::get('app_report_safe_times_post', 0);
                if($app_report_safe_times_post == 0){
                    $app_report_safe_times_post = 999;
                }
                if(UserUtils::is_mini_admin($uid)){
                    if($report_type == 10){
                        WxPost::where('id', $object_id)->update(['is_blur'=>1]);
                    }else{
                        WxPost::where('id', $object_id)->update(['posts_state'=>2]);
                        UserUtils::assistant_notice('admin', '管理员id：'.$uid.'对该贴(<a href="/pages/sticky/sticky?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，已被系统自动下架。');
                    }

                }else if($count_ > $app_report_safe_times_post){
                    if($report_type == 10){
                        WxPost::where('id', $object_id)->update(['is_blur'=>1]);
                    }else{
                        WxPost::where('id', $object_id)->update(['posts_state'=>2]);
                        UserUtils::assistant_notice('admin', '多名用户对该贴(<a href="/pages/sticky/sticky?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，并且超过最大次数，已被系统自动下架。');
                    }
                }else{
                    UserUtils::assistant_notice('admin', '有新的用户(id: <a href="/pages/user/user?id='.$uid.'">'.$uid.'</a>)对该贴(<a href="/pages/sticky/sticky?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报。');
                }
            }else if($type == 1){
                $app_report_safe_times_comment = Settings::get('app_report_safe_times_comment', 0);
                if($app_report_safe_times_comment == 0){
                    $app_report_safe_times_comment = 999;
                }
                $posts_id = WxComment::where('id', $object_id)->value('posts_id');
                if(UserUtils::is_mini_admin($uid)){
                    WxComment::where('id', $object_id)->update(['comment_state'=>2]);
                    UserUtils::assistant_notice('admin', '管理员id：'.$uid.'对评论(<a href="/pages/sticky/sticky?id='.$posts_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，已被系统自动下架。');
                }else if($count_ > $app_report_safe_times_comment){
                    WxComment::where('id', $object_id)->update(['comment_state'=>2]);
                    UserUtils::assistant_notice('admin', '多名用户对评论(<a href="/pages/sticky/sticky?id='.$posts_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，并且超过最大次数，已被系统自动下架。');
                }else{
                    UserUtils::assistant_notice('admin', '有新的用户(id: <a href="/pages/user/user?id='.$uid.'">'.$uid.'</a>)对评论(<a href="/pages/sticky/sticky?id='.$posts_id.'" target="_blank">id: '.$object_id.'</a>)进行举报。');
                }
            }else if($type == 2){
                $app_report_safe_times_user = Settings::get('app_report_safe_times_user', 0);
                if($app_report_safe_times_user == 0){
                    $app_report_safe_times_user = 999;
                }
                $the_user = WxUser::find($object_id);
                if(UserUtils::is_mini_admin($uid)){
                    UserUtils::lock_user_incre($the_user, 3, 3600 * 24 * 7, '该用户被管理员举报');
                    UserUtils::assistant_notice('admin', '管理员id：'.$uid.'对该用户(<a href="/pages/user/user?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，已被系统禁言7天。');
                }else if($count_ > $app_report_safe_times_user){
                    UserUtils::lock_user_incre($the_user, 3, 3600 * 24 * 7, '该用户被人多次举报');
                    UserUtils::assistant_notice('admin', '多名用户对该用户(<a href="/pages/user/user?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，并且超过最大次数，已被系统禁言7天。');
                }else{
                    UserUtils::assistant_notice('admin', '有新的用户(id: <a href="/pages/user/user?id='.$uid.'">'.$uid.'</a>)对该用户(<a href="/pages/user/user?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报。');
                }
            }else if($type == 3){
                // 举报商品
            }else if($type == 4){
                // 举报圈子
                $app_report_safe_times_circle = Settings::get('app_report_safe_times_circle', 0);
                if($app_report_safe_times_circle == 0){
                    $app_report_safe_times_circle = 999;
                }
                if(UserUtils::is_mini_admin($uid)){
                    WxCircle::where('id', $object_id)->update(['circle_state'=>2]);
                    UserUtils::assistant_notice('admin', '管理员id：'.$uid.'对该圈子(<a href="/pages/circle/list?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，已被系统自动驳回。');
                }else if($count_ > $app_report_safe_times_circle){
                    WxUser::where('id', $object_id)->update(['circle_state'=>2]);
                    UserUtils::assistant_notice('admin', '多名用户对该圈子(<a href="/pages/circle/list?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，并且超过最大次数，已被系统自动驳回。');
                }else{
                    UserUtils::assistant_notice('admin', '有新的用户(id: <a href="/pages/user/user?id='.$uid.'">'.$uid.'</a>)对该圈子(<a href="/pages/circle/list?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报。');
                }
            }else if($type == 5){
                // 举报圈子
                $app_report_safe_times_bureau = Settings::get('app_report_safe_times_bureau', 0);
                if($app_report_safe_times_bureau == 0){
                    $app_report_safe_times_bureau = 999;
                }
                if(UserUtils::is_mini_admin($uid)){
                    WxBureau::where('id', $object_id)->update(['status'=>4]);
                    UserUtils::assistant_notice('admin', '管理员id：'.$uid.'对该组局(<a href="/pagesZ/organize-bureau/details/index?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，已被系统自动驳回。');
                }else if($count_ > $app_report_safe_times_bureau){
                    WxBureau::where('id', $object_id)->update(['status'=>4]);
                    UserUtils::assistant_notice('admin', '多名用户对该组局(<a href="/pagesZ/organize-bureau/details/index?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，并且超过最大次数，已被系统自动驳回。');
                }else{
                    UserUtils::assistant_notice('admin', '有新的用户(id: <a href="/pages/user/user?id='.$uid.'">'.$uid.'</a>)对该组局(<a href="/pagesZ/organize-bureau/details/index?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报。');
                }
            }else if($type == 6){
                // 举报圈子
                $app_report_safe_times_voter = Settings::get('app_report_safe_times_voter', 0);
                if($app_report_safe_times_voter == 0){
                    $app_report_safe_times_voter = 999;
                }
                if(UserUtils::is_mini_admin($uid)){
                    WxVoter::where('id', $object_id)->update(['status'=>2]);
                    UserUtils::assistant_notice('admin', '管理员id：'.$uid.'对该选票(<a href="/pagesV/voter/detail/detail?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，已被系统自动驳回。');
                }else if($count_ > $app_report_safe_times_voter){
                    WxVoter::where('id', $object_id)->update(['status'=>2]);
                    UserUtils::assistant_notice('admin', '多名用户对该选票(<a href="/pagesV/voter/detail/detail?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报，并且超过最大次数，已被系统自动驳回。');
                }else{
                    UserUtils::assistant_notice('admin', '有新的用户(id: <a href="/pages/user/user?id='.$uid.'">'.$uid.'</a>)对该选票(<a href="/pagesV/voter/detail/detail?id='.$object_id.'" target="_blank">id: '.$object_id.'</a>)进行举报。');
                }
            }
            UserInputSafeCheckJob::dispatch($uid, $report_content);
            Utils::image_state_change($image_urls__, 1);

            return $this->success($r);
        }else{
            return $this->fail(200002);
        }
    }

}
